problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
βŒ€
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
D. Boxes And Ballstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan has n different boxes. The first of them contains some balls of n different colors.Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≀ i ≀ n) i-th box will contain all balls with color i.In order to do this, Ivan will make some turns. Each turn he does the following: Ivan chooses any non-empty box and takes all balls from this box; Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3. The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.Help Ivan to determine the minimum possible penalty of the game!InputThe first line contains one integer number n (1 ≀ n ≀ 200000) β€” the number of boxes and colors.The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the number of balls with color i.OutputPrint one number β€” the minimum possible penalty of the game.ExamplesInput31 2 3Output6Input42 3 4 5Output19NoteIn the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.In the second example you make two turns: Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 β€” to the fourth box and the rest put back into the first box. Penalty is 14; Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 β€” to the second box. Penalty is 5. Total penalty is 19.
Input31 2 3
Output6
2 seconds
256 megabytes
['data structures', 'greedy', '*2300']
C. Bertown Subwaytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i; For each station i there exists exactly one station j such that pj = i. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≀ x, y ≀ n).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! InputThe first line contains one integer number n (1 ≀ n ≀ 100000) β€” the number of stations.The second line contains n integer numbers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the current structure of the subway. All these numbers are distinct.OutputPrint one number β€” the maximum possible value of convenience.ExamplesInput32 1 3Output9Input51 5 4 3 2Output17NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).In the second example the mayor can change p2 to 4 and p3 to 5.
Input32 1 3
Output9
1 second
256 megabytes
['dfs and similar', 'greedy', 'math', '*1500']
B. Japanese Crosswords Strike Backtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example: If x = 6 and the crossword is 111011, then its encoding is an array {3, 2}; If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1}; If x = 5 and the crossword is 11111, then its encoding is an array {5}; If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!InputThe first line contains two integer numbers n and x (1 ≀ n ≀ 100000, 1 ≀ x ≀ 109) β€” the number of elements in the encoding and the length of the crossword Mishka picked.The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 10000) β€” the encoding.OutputPrint YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.ExamplesInput2 41 3OutputNOInput3 103 3 2OutputYESInput2 101 3OutputNO
Input2 41 3
OutputNO
1 second
256 megabytes
['implementation', '*1100']
A. Book Readingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading.Help Luba to determine the minimum number of day when she finishes reading.It is guaranteed that the answer doesn't exceed n.Remember that there are 86400 seconds in a day.InputThe first line contains two integers n and t (1 ≀ n ≀ 100, 1 ≀ t ≀ 106) β€” the number of days and the time required to read the book.The second line contains n integers ai (0 ≀ ai ≀ 86400) β€” the time Luba has to spend on her work during i-th day.OutputPrint the minimum day Luba can finish reading the book.It is guaranteed that answer doesn't exceed n.ExamplesInput2 286400 86398Output2Input2 864000 86400Output1
Input2 286400 86398
Output2
2 seconds
256 megabytes
['implementation', '*800']
M. Quadcopter Competitiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp takes part in a quadcopter competition. According to the rules a flying robot should: start the race from some point of a field, go around the flag, close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (x1, y1) and the coordinates of the point where the flag is situated (x2, y2). Polycarp’s quadcopter can fly only parallel to the sides of the field each tick changing exactly one coordinate by 1. It means that in one tick the quadcopter can fly from the point (x, y) to any of four points: (x - 1, y), (x + 1, y), (x, y - 1) or (x, y + 1).Thus the quadcopter path is a closed cycle starting and finishing in (x1, y1) and containing the point (x2, y2) strictly inside. The picture corresponds to the first example: the starting (and finishing) point is in (1, 5) and the flag is in (5, 2). What is the minimal length of the quadcopter path?InputThe first line contains two integer numbers x1 and y1 ( - 100 ≀ x1, y1 ≀ 100) β€” coordinates of the quadcopter starting (and finishing) point.The second line contains two integer numbers x2 and y2 ( - 100 ≀ x2, y2 ≀ 100) β€” coordinates of the flag.It is guaranteed that the quadcopter starting point and the flag do not coincide.OutputPrint the length of minimal path of the quadcopter to surround the flag and return back.ExamplesInput1 55 2Output18Input0 10 0Output8
Input1 55 2
Output18
3 seconds
256 megabytes
['greedy', 'math', '*1100']
L. Berland.Taxitime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland.Taxi is a new taxi company with k cars which started operating in the capital of Berland just recently. The capital has n houses on a straight line numbered from 1 (leftmost) to n (rightmost), and the distance between any two neighboring houses is the same.You have to help the company schedule all the taxi rides which come throughout the day according to the following rules: All cars are available for picking up passengers. Initially the j-th car is located next to the house with the number xj at time 0. All cars have the same speed. It takes exactly 1 minute for any car to travel between neighboring houses i and i + 1. The i-th request for taxi ride comes at the time ti, asking for a passenger to be picked up at the house ai and dropped off at the house bi. All requests for taxi rides are given in the increasing order of ti. All ti are distinct. When a request for taxi ride is received at time ti, Berland.Taxi operator assigns a car to it as follows: Out of cars which are currently available, operator assigns the car which is the closest to the pick up spot ai. Needless to say, if a car is already on a ride with a passenger, it won't be available for any rides until that passenger is dropped off at the corresponding destination. If there are several such cars, operator will pick one of them which has been waiting the most since it became available. If there are several such cars, operator will pick one of them which has the lowest number. After a car gets assigned to the taxi ride request: The driver immediately starts driving from current position to the house ai. Once the car reaches house ai, the passenger is immediately picked up and the driver starts driving to house bi. Once house bi is reached, the passenger gets dropped off and the car becomes available for new rides staying next to the house bi. It is allowed for multiple cars to be located next to the same house at the same point in time, while waiting for ride requests or just passing by. If there are no available cars at time ti when a request for taxi ride comes, then: The i-th passenger will have to wait for a car to become available. When a car becomes available, operator will immediately assign it to this taxi ride request. If multiple cars become available at once while the passenger is waiting, operator will pick a car out of them according to the rules described above. Operator processes taxi ride requests one by one. So if multiple passengers are waiting for the cars to become available, operator will not move on to processing the (i + 1)-th ride request until the car gets assigned to the i-th ride request.Your task is to write a program that will process the given list of m taxi ride requests. For each request you have to find out which car will get assigned to it, and how long the passenger will have to wait for a car to arrive. Note, if there is already car located at the house ai, then the corresponding wait time will be 0.InputThe first line of input contains integers n, k and m (2 ≀ n ≀ 2Β·105, 1 ≀ k, m ≀ 2Β·105) β€” number of houses, number of cars, and number of taxi ride requests. The second line contains integers x1, x2, ..., xk (1 ≀ xi ≀ n) β€” initial positions of cars. xi is a house number at which the i-th car is located initially. It's allowed for more than one car to be located next to the same house.The following m lines contain information about ride requests. Each ride request is represented by integers tj, aj and bj (1 ≀ tj ≀ 1012, 1 ≀ aj, bj ≀ n, aj ≠ bj), where tj is time in minutes when a request is made, aj is a house where passenger needs to be picked up, and bj is a house where passenger needs to be dropped off. All taxi ride requests are given in the increasing order of tj. All tj are distinct.OutputPrint m lines: the j-th line should contain two integer numbers, the answer for the j-th ride request β€” car number assigned by the operator and passenger wait time.ExamplesInput10 1 235 2 89 10 3Output1 11 5Input5 2 11 510 3 5Output1 2Input5 2 21 510 3 520 4 1Output1 22 1NoteIn the first sample test, a request comes in at time 5 and the car needs to get from house 3 to house 2 to pick up the passenger. Therefore wait time will be 1 and the ride will be completed at time 5 + 1 + 6 = 12. The second request comes in at time 9, so the passenger will have to wait for the car to become available at time 12, and then the car needs another 2 minutes to get from house 8 to house 10. So the total wait time is 3 + 2 = 5. In the second sample test, cars 1 and 2 are located at the same distance from the first passenger and have the same "wait time since it became available". Car 1 wins a tiebreaker according to the rules because it has the lowest number. It will come to house 3 at time 3, so the wait time will be 2.
Input10 1 235 2 89 10 3
Output1 11 5
3 seconds
256 megabytes
['data structures', '*2500']
K. Road Wideningtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.The street is split into n equal length parts from left to right, the i-th part is characterized by two integers: width of road si and width of lawn gi. For each of n parts the Mayor should decide the size of lawn to demolish. For the i-th part he can reduce lawn width by integer xi (0 ≀ xi ≀ gi). After it new road width of the i-th part will be equal to s'i = si + xi and new lawn width will be equal to g'i = gi - xi.On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each i (1 ≀ i < n) the inequation |s'i + 1 - s'i| ≀ 1 should hold. Initially this condition might not be true.You need to find the the total width of lawns the Mayor will destroy according to his plan.InputThe first line contains integer n (1 ≀ n ≀ 2Β·105) β€” number of parts of the street.Each of the following n lines contains two integers si, gi (1 ≀ si ≀ 106, 0 ≀ gi ≀ 106) β€” current width of road and width of the lawn on the i-th part of the street.OutputIn the first line print the total width of lawns which will be removed.In the second line print n integers s'1, s'2, ..., s'n (si ≀ s'i ≀ si + gi) β€” new widths of the road starting from the first part and to the last.If there is no solution, print the only integer -1 in the first line.ExamplesInput34 54 54 10Output169 9 10 Input41 100100 11 100100 1Output202101 101 101 101 Input31 1100 1001 1Output-1
Input34 54 54 10
Output169 9 10
3 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1800']
J. Renovationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe mayor of the Berland city S sees the beauty differently than other city-dwellers. In particular, he does not understand at all, how antique houses can be nice-looking. So the mayor wants to demolish all ancient buildings in the city.The city S is going to host the football championship very soon. In order to make the city beautiful, every month the Berland government provides mayor a money tranche. The money has to be spent on ancient buildings renovation.There are n months before the championship and the i-th month tranche equals to ai burles. The city S has m antique buildings and the renovation cost of the j-th building is bj burles.The mayor has his own plans for spending the money. As he doesn't like antique buildings he wants to demolish as much of them as possible. For the j-th building he calculated its demolishing cost pj.The mayor decided to act according to the following plan.Each month he chooses several (possibly zero) of m buildings to demolish in such a way that renovation cost of each of them separately is not greater than the money tranche ai of this month (bj ≀ ai)Β β€” it will allow to deceive city-dwellers that exactly this building will be renovated.Then the mayor has to demolish all selected buildings during the current month as otherwise the dwellers will realize the deception and the plan will fail. Definitely the total demolishing cost can not exceed amount of money the mayor currently has. The mayor is not obliged to spend all the money on demolishing. If some money is left, the mayor puts it to the bank account and can use it in any subsequent month. Moreover, at any month he may choose not to demolish any buildings at all (in this case all the tranche will remain untouched and will be saved in the bank).Your task is to calculate the maximal number of buildings the mayor can demolish.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 100 000)Β β€” the number of months before the championship and the number of ancient buildings in the city S.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the tranche of the i-th month.The third line contains m integers b1, b2, ..., bm (1 ≀ bj ≀ 109), where bj is renovation cost of the j-th building.The fourth line contains m integers p1, p2, ..., pm (1 ≀ pj ≀ 109), where pj is the demolishing cost of the j-th building.OutputOutput single integerΒ β€” the maximal number of buildings the mayor can demolish.ExamplesInput2 32 46 2 31 3 2Output2Input3 55 3 15 2 9 1 104 2 1 3 10Output3Input5 66 3 2 4 33 6 4 5 4 21 4 3 2 5 3Output6NoteIn the third example the mayor acts as follows.In the first month he obtains 6 burles tranche and demolishes buildings #2 (renovation cost 6, demolishing cost 4) and #4 (renovation cost 5, demolishing cost 2). He spends all the money on it.After getting the second month tranche of 3 burles, the mayor selects only building #1 (renovation cost 3, demolishing cost 1) for demolishing. As a result, he saves 2 burles for the next months.In the third month he gets 2 burle tranche, but decides not to demolish any buildings at all. As a result, he has 2 + 2 = 4 burles in the bank.This reserve will be spent on the fourth month together with the 4-th tranche for demolishing of houses #3 and #5 (renovation cost is 4 for each, demolishing costs are 3 and 5 correspondingly). After this month his budget is empty.Finally, after getting the last tranche of 3 burles, the mayor demolishes building #6 (renovation cost 2, demolishing cost 3).As it can be seen, he demolished all 6 buildings.
Input2 32 46 2 31 3 2
Output2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*2400']
I. Photo Processingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy has found one more cool application to process photos. However the application has certain limitations.Each photo i has a contrast vi. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible.Evlampiy already knows the contrast vi for each of his n photos. Now he wants to split the photos into groups, so that each group contains at least k photos. As a result, each photo must belong to exactly one group.He considers a processing time of the j-th group to be the difference between the maximum and minimum values of vi in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups.Split n photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible.InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 3Β·105) β€” number of photos and minimum size of a group.The second line contains n integers v1, v2, ..., vn (1 ≀ vi ≀ 109), where vi is the contrast of the i-th photo.OutputPrint the minimal processing time of the division into groups.ExamplesInput5 250 110 130 40 120Output20Input4 12 3 4 1Output0NoteIn the first example the photos should be split into 2 groups: [40, 50] and [110, 120, 130]. The processing time of the first group is 10, and the processing time of the second group is 20. Maximum among 10 and 20 is 20. It is impossible to split the photos into groups in a such way that the processing time of division is less than 20.In the second example the photos should be split into four groups, each containing one photo. So the minimal possible processing time of a division is 0.
Input5 250 110 130 40 120
Output20
3 seconds
256 megabytes
['binary search', 'dp', '*1900']
H. Palindromic Cuttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.InputThe first line contains an integer n (1 ≀ n ≀ 4Β·105) β€” the length of string s.The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.OutputPrint to the first line an integer k β€” minimum number of palindromes into which you can cut a given string.Print to the second line k strings β€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.ExamplesInput6aabaacOutput2aba aca Input80rTrT022Output102TrrT20 Input2aAOutput2a A
Input6aabaac
Output2aba aca
3 seconds
256 megabytes
['brute force', 'implementation', 'strings', '*1800']
G. Orientation of Edgestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans.Help Vasya find the plans.InputThe first line contains three integers n, m and s (2 ≀ n ≀ 3Β·105, 1 ≀ m ≀ 3Β·105, 1 ≀ s ≀ n) β€” number of vertices and edges in the graph, and the vertex Vasya has picked.The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≀ ti ≀ 2, 1 ≀ ui, vi ≀ n, ui ≠ vi) β€” edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi.It is guaranteed that there is at least one undirected edge in the graph.OutputThe first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices.A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input.If there are multiple solutions, print any of them.ExamplesInput2 2 11 1 22 2 1Output2-2+Input6 6 32 2 61 4 52 3 41 4 11 3 12 2 3Output6++-2+-+
Input2 2 11 1 22 2 1
Output2-2+
3 seconds
256 megabytes
['dfs and similar', 'graphs', '*1900']
F. Lost in Transliterationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are some ambiguities when one writes Berland names with the letters of the Latin alphabet.For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?Formally, we assume that two words denote the same name, if using the replacements "u"Β Β "oo" and "h"Β Β "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.For example, the following pairs of words denote the same name: "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" "kuuper" and "kuooper" "kuuper". "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" "khoon" and "kkkhoon" "kkhoon" "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name.InputThe first line contains integer number n (2 ≀ n ≀ 400) β€” number of the words in the list.The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.OutputPrint the minimal number of groups where the words in each group denote the same name.ExamplesInput10mihailoolyanakooooperhoonulyanakooupermikhailkhunkuooperkkkhoonOutput4Input9haritonhkaritonbuoikkkharitonboooibuikharitonbouiboiOutput5Input2alexalexOutput1NoteThere are four groups of words in the first example. Words in each group denote same name: "mihail", "mikhail" "oolyana", "ulyana" "kooooper", "koouper" "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: "hariton", "kkkhariton", "khariton" "hkariton" "buoi", "boooi", "boui" "bui" "boi" In the third example the words are equal, so they denote the same name.
Input10mihailoolyanakooooperhoonulyanakooupermikhailkhunkuooperkkkhoon
Output4
3 seconds
256 megabytes
['implementation', '*1300']
E. Field of Wonderstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.InputThe first line contains one integer n (1 ≀ n ≀ 50) β€” the length of the hidden word.The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed.The third line contains an integer m (1 ≀ m ≀ 1000) β€” the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves β€” n-letter strings of lowercase Latin letters. All words are distinct.It is guaranteed that the hidden word appears as one of the given m words. Before the current move Polycarp has told exactly the letters which are currently revealed.OutputOutput the single integer β€” the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero.ExamplesInput4a**d2abcdacbdOutput2Input5lo*er2loverloserOutput0Input3a*a2aaaabaOutput1NoteIn the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed.The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word.In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns.
Input4a**d2abcdacbd
Output2
3 seconds
256 megabytes
['implementation', 'strings', '*1500']
D. Packmen Strike Backtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGame field is represented by a line of n square cells. In some cells there are packmen, in some cells there are asterisks and the rest of the cells are empty. Packmen eat asterisks.Before the game starts you can choose a movement direction, left or right, for each packman. Once the game begins all the packmen simultaneously start moving according their directions. A packman can't change the given direction.Once a packman enters a cell containing an asterisk, packman immediately eats the asterisk. Once the packman leaves the cell it becomes empty. Each packman moves at speed 1 cell per second. If a packman enters a border cell, the packman stops. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions.Your task is to assign a direction to each packman so that they eat the maximal number of asterisks. If there are multiple ways to assign directions to eat the maximal number of asterisks, you should choose the way which minimizes the time to do that.InputThe first line contains integer number n (2 ≀ n ≀ 1 000 000) β€” the number of cells in the game field.The second line contains n characters. If the i-th character is '.', the i-th cell is empty. If the i-th character is '*', the i-th cell contains an asterisk. If the i-th character is 'P', the i-th cell contains a packman.The field contains at least one asterisk and at least one packman.OutputPrint two integer numbers β€” the maximal number of asterisks packmen can eat and the minimal time to do it.ExamplesInput6*.P*P*Output3 4Input8*...P..*Output1 3NoteIn the first example the leftmost packman should move to the right, the rightmost packman should move to the left. All the asterisks will be eaten, the last asterisk will be eaten after 4 seconds.
Input6*.P*P*
Output3 4
3 seconds
256 megabytes
['binary search', 'dp', 'math', '*2500']
C. Downloading B++time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnly T milliseconds left before the start of well-known online programming contest Codehorses Round 2017.Polycarp needs to download B++ compiler to take part in the contest. The size of the file is f bytes.Polycarp's internet tariff allows to download data at the rate of one byte per t0 milliseconds. This tariff is already prepaid, and its use does not incur any expense for Polycarp. In addition, the Internet service provider offers two additional packages: download a1 bytes at the rate of one byte per t1 milliseconds, paying p1 burles for the package; download a2 bytes at the rate of one byte per t2 milliseconds, paying p2 burles for the package. Polycarp can buy any package many times. When buying a package, its price (p1 or p2) is prepaid before usage. Once a package is bought it replaces the regular tariff until package data limit is completely used. After a package is consumed Polycarp can immediately buy a new package or switch to the regular tariff without loosing any time. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.Find the minimum amount of money Polycarp has to spend to download an f bytes file no more than in T milliseconds.Note that because of technical reasons Polycarp can download only integer number of bytes using regular tariff and both packages. I.e. in each of three downloading modes the number of downloaded bytes will be integer. It means that Polycarp can't download a byte partially using the regular tariff or/and both packages.InputThe first line contains three integer numbers f, T and t0 (1 ≀ f, T, t0 ≀ 107) β€” size of the file to download (in bytes), maximal time to download the file (in milliseconds) and number of milliseconds to download one byte using the regular internet tariff.The second line contains a description of the first additional package. The line contains three integer numbers a1, t1 and p1 (1 ≀ a1, t1, p1 ≀ 107), where a1 is maximal sizes of downloaded data (in bytes), t1 is time to download one byte (in milliseconds), p1 is price of the package (in burles).The third line contains a description of the second additional package. The line contains three integer numbers a2, t2 and p2 (1 ≀ a2, t2, p2 ≀ 107), where a2 is maximal sizes of downloaded data (in bytes), t2 is time to download one byte (in milliseconds), p2 is price of the package (in burles).Polycarp can buy any package many times. Once package is bought it replaces the regular tariff until package data limit is completely used. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.OutputPrint the minimum amount of money that Polycarp needs to pay to download B++ compiler no more than in T milliseconds. If there is no solution, print the only integer -1.ExamplesInput120 964 2026 8 813 10 4Output40Input10 200 201 1 12 2 3Output0Input8 81 114 10 163 10 12Output28Input8 79 114 10 163 10 12Output-1NoteIn the first example Polycarp has to buy the first additional package 5 times and do not buy the second additional package. He downloads 120 bytes (of total 26Β·5 = 130 bytes) in 120Β·8 = 960 milliseconds (960 ≀ 964). He spends 8Β·5 = 40 burles on it.In the second example Polycarp has enough time to download 10 bytes. It takes 10Β·20 = 200 milliseconds which equals to upper constraint on download time.In the third example Polycarp has to buy one first additional package and one second additional package.In the fourth example Polycarp has no way to download the file on time.
Input120 964 2026 8 813 10 4
Output40
3 seconds
256 megabytes
['binary search', 'implementation', '*2300']
B. Berland Armytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n military men in the Berland army. Some of them have given orders to other military men by now. Given m pairs (xi, yi), meaning that the military man xi gave the i-th order to another military man yi.It is time for reform! The Berland Ministry of Defence plans to introduce ranks in the Berland army. Each military man should be assigned a rank β€” integer number between 1 and k, inclusive. Some of them have been already assigned a rank, but the rest of them should get a rank soon.Help the ministry to assign ranks to the rest of the army so that: for each of m orders it is true that the rank of a person giving the order (military man xi) is strictly greater than the rank of a person receiving the order (military man yi); for each rank from 1 to k there is at least one military man with this rank. InputThe first line contains three integers n, m and k (1 ≀ n ≀ 2Β·105, 0 ≀ m ≀ 2Β·105, 1 ≀ k ≀ 2Β·105) β€” number of military men in the Berland army, number of orders and number of ranks.The second line contains n integers r1, r2, ..., rn, where ri > 0 (in this case 1 ≀ ri ≀ k) means that the i-th military man has been already assigned the rank ri; ri = 0 means the i-th military man doesn't have a rank yet.The following m lines contain orders one per line. Each order is described with a line containing two integers xi, yi (1 ≀ xi, yi ≀ n, xi ≠ yi). This line means that the i-th order was given by the military man xi to the military man yi. For each pair (x, y) of military men there could be several orders from x to y.OutputPrint n integers, where the i-th number is the rank of the i-th military man. If there are many solutions, print any of them.If there is no solution, print the only number -1.ExamplesInput5 3 30 3 0 0 22 43 43 5Output1 3 3 2 2 Input7 6 50 4 5 4 1 0 06 13 63 17 57 17 4Output2 4 5 4 1 3 5 Input2 2 22 11 22 1Output-1
Input5 3 30 3 0 0 22 43 43 5
Output1 3 3 2 2
3 seconds
256 megabytes
['constructive algorithms', 'graphs', 'greedy', '*2600']
A. Automatic Doortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an automatic door at the entrance of a factory. The door works in the following way: when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside, when one or several people come to the door and it is open, all people immediately come inside, opened door immediately closes in d seconds after its opening, if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close. For example, if d = 3 and four people are coming at four different moments of time t1 = 4, t2 = 7, t3 = 9 and t4 = 13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12.It is known that n employees will enter at moments a, 2Β·a, 3Β·a, ..., nΒ·a (the value a is positive integer). Also m clients will enter at moments t1, t2, ..., tm.Write program to find the number of times the automatic door will open. Assume that the door is initially closed.InputThe first line contains four integers n, m, a and d (1 ≀ n, a ≀ 109, 1 ≀ m ≀ 105, 1 ≀ d ≀ 1018) β€” the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes.The second line contains integer sequence t1, t2, ..., tm (1 ≀ ti ≀ 1018) β€” moments of time when clients will come. The values ti are given in non-decreasing order.OutputPrint the number of times the door will open.ExamplesInput1 1 3 47Output1Input4 3 4 27 9 11Output4NoteIn the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time.
Input1 1 3 47
Output1
1 second
256 megabytes
['implementation', '*2200']
B. Table Tennistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.InputThe first line contains two integers: n and k (2 ≀ n ≀ 500, 2 ≀ k ≀ 1012)Β β€” the number of people and the number of wins.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n) β€” powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.OutputOutput a single integer β€” power of the winner.ExamplesInput2 21 2Output2 Input4 23 1 2 4Output3 Input6 26 5 3 1 2 4Output6 Input2 100000000002 1Output2NoteGames in the second sample:3 plays with 1. 3 wins. 1 goes to the end of the line.3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.
Input2 21 2
Output2
2 seconds
256 megabytes
['data structures', 'implementation', '*1200']
A. Borya's Diagnosistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?InputFirst line contains an integer n β€” number of doctors (1 ≀ n ≀ 1000). Next n lines contain two numbers si and di (1 ≀ si, di ≀ 1000).OutputOutput a single integer β€” the minimum day at which Borya can visit the last doctor.ExamplesInput32 21 22 2Output4Input210 16 5Output11NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11.
Input32 21 22 2
Output4
2 seconds
256 megabytes
['implementation', '*900']
E. Numbers on the blackboardtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA sequence of n integers is written on a blackboard. Soon Sasha will come to the blackboard and start the following actions: let x and y be two adjacent numbers (x before y), then he can remove them and write x + 2y instead of them. He will perform these operations until one number is left. Sasha likes big numbers and will get the biggest possible number.Nikita wants to get to the blackboard before Sasha and erase some of the numbers. He has q options, in the option i he erases all numbers to the left of the li-th number and all numbers to the right of ri-th number, i.Β e. all numbers between the li-th and the ri-th, inclusive, remain on the blackboard. For each of the options he wants to know how big Sasha's final number is going to be. This number can be very big, so output it modulo 109 + 7.InputThe first line contains two integers n and q (1 ≀ n, q ≀ 105) β€” the number of integers on the blackboard and the number of Nikita's options.The next line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109)Β β€” the sequence on the blackboard.Each of the next q lines contains two integers li and ri (1 ≀ li ≀ ri ≀ n), describing Nikita's options.OutputFor each option output Sasha's result modulo 109 + 7.ExamplesInput3 31 2 31 31 22 3Output1758Input3 11 2 -31 3Output1000000006Input4 21 1 1 -11 43 4Output51000000006NoteIn the second sample Nikita doesn't erase anything. Sasha first erases the numbers 1 and 2 and writes 5. Then he erases 5 and -3 and gets -1. -1 modulo 109 + 7 is 109 + 6.
Input3 31 2 31 31 22 3
Output1758
2 seconds
512 megabytes
['combinatorics', 'dp', '*3300']
D. Magic Breedingtime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputNikita and Sasha play a computer game where you have to breed some magical creatures. Initially, they have k creatures numbered from 1 to k. Creatures have n different characteristics.Sasha has a spell that allows to create a new creature from two given creatures. Each of its characteristics will be equal to the maximum of the corresponding characteristics of used creatures. Nikita has a similar spell, but in his spell, each characteristic of the new creature is equal to the minimum of the corresponding characteristics of used creatures. A new creature gets the smallest unused number.They use their spells and are interested in some characteristics of their new creatures. Help them find out these characteristics.InputThe first line contains integers n, k and q (1 ≀ n ≀ 105, 1 ≀ k ≀ 12, 1 ≀ q ≀ 105) β€” number of characteristics, creatures and queries.Next k lines describe original creatures. The line i contains n numbers ai1, ai2, ..., ain (1 ≀ aij ≀ 109)Β β€” characteristics of the i-th creature.Each of the next q lines contains a query. The i-th of these lines contains numbers ti, xi and yi (1 ≀ ti ≀ 3). They denote a query: ti = 1 means that Sasha used his spell to the creatures xi and yi. ti = 2 means that Nikita used his spell to the creatures xi and yi. ti = 3 means that they want to know the yi-th characteristic of the xi-th creature. In this case 1 ≀ yi ≀ n. It's guaranteed that all creatures' numbers are valid, that means that they are created before any of the queries involving them.OutputFor each query with ti = 3 output the corresponding characteristic.ExamplesInput2 2 41 22 11 1 22 1 23 3 13 4 2Output21Input5 3 81 2 3 4 55 1 2 3 44 5 1 2 31 1 21 2 32 4 53 6 13 6 23 6 33 6 43 6 5Output52234NoteIn the first sample, Sasha makes a creature with number 3 and characteristics (2, 2). Nikita makes a creature with number 4 and characteristics (1, 1). After that they find out the first characteristic for the creature 3 and the second characteristic for the creature 4.
Input2 2 41 22 11 1 22 1 23 3 13 4 2
Output21
4 seconds
1024 megabytes
['bitmasks', '*2900']
C. Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently a tournament in k kinds of sports has begun in Berland. Vasya wants to make money on the bets.The scheme of the tournament is very mysterious and not fully disclosed. Competitions are held back to back, each of them involves two sportsmen who have not left the tournament yet. Each match can be held in any of the k kinds of sport. Loser leaves the tournament. The last remaining sportsman becomes the winner. Apart of this, the scheme can be arbitrary, it is not disclosed in advance.Vasya knows powers of sportsmen in each kind of sport. He believes that the sportsmen with higher power always wins.The tournament is held every year, and each year one new participant joins it. In the first tournament, only one sportsman has participated, in the second there were two sportsmen, and so on. Vasya has been watching the tournament for the last n years. Help him to find the number of possible winners for each of the n tournaments.InputThe first line contains two integers n and k (1 ≀ n ≀ 5Β·104, 1 ≀ k ≀ 10) β€” the number of tournaments and the number of kinds of sport, respectively.Each of the next n lines contains k integers si1, si2, ..., sik (1 ≀ sij ≀ 109), where sij is the power of the i-th sportsman in the j-th kind of sport. The sportsman with higher powers always wins. It's guaranteed that for any kind of sport all of these powers are distinct.OutputFor each of the n tournaments output the number of contenders who can win.ExamplesInput3 21 55 110 10Output121Input3 22 23 31 10Output113Input3 22 31 13 2Output112NoteIn the first sample:In the first tournament there is only one sportsman, and he is the winner.In the second tournament, there are two sportsmen, and everyone can defeat another, depending on kind of sports.In the third tournament, the third sportsman in the strongest in both kinds of sports, so he is the winner regardless of the scheme.
Input3 21 55 110 10
Output121
2 seconds
256 megabytes
['data structures', 'graphs', '*2700']
B. Teams Formationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai.Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i.Β e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times).After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.InputThe first line contains three integers n, k and m (1 ≀ n ≀ 105, 2 ≀ k ≀ 109, 1 ≀ m ≀ 109).The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 105), where ai is the number of city, person from which must take seat i in the bus. OutputOutput the number of remaining participants in the line.ExamplesInput4 2 51 2 3 1Output12Input1 9 101Output1Input3 2 101 2 1Output0NoteIn the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.
Input4 2 51 2 3 1
Output12
2 seconds
256 megabytes
['data structures', 'implementation', '*2300']
A. Short Programtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.InputThe first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines.Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023.OutputOutput an integer k (0 ≀ k ≀ 5) β€” the length of your program.Next k lines must contain commands in the same format as in the input.ExamplesInput3| 3^ 2| 1Output2| 3^ 2Input3& 1& 3& 5Output1& 1Input3^ 1^ 2^ 3Output0NoteYou can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.Second sample:Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
Input3| 3^ 2| 1
Output2| 3^ 2
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', '*1600']
F. Ann and Bookstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Ann's favorite book shop are as many as n books on math and economics. Books are numbered from 1 to n. Each of them contains non-negative number of problems.Today there is a sale: any subsegment of a segment from l to r can be bought at a fixed price. Ann decided that she wants to buy such non-empty subsegment that the sale operates on it and the number of math problems is greater than the number of economics problems exactly by k. Note that k may be positive, negative or zero.Unfortunately, Ann is not sure on which segment the sale operates, but she has q assumptions. For each of them she wants to know the number of options to buy a subsegment satisfying the condition (because the time she spends on choosing depends on that).Currently Ann is too busy solving other problems, she asks you for help. For each her assumption determine the number of subsegments of the given segment such that the number of math problems is greaten than the number of economics problems on that subsegment exactly by k.InputThe first line contains two integers n and k (1 ≀ n ≀ 100 000,  - 109 ≀ k ≀ 109) β€” the number of books and the needed difference between the number of math problems and the number of economics problems.The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 2), where ti is 1 if the i-th book is on math or 2 if the i-th is on economics.The third line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 109), where ai is the number of problems in the i-th book.The fourth line contains a single integer q (1 ≀ q ≀ 100 000) β€” the number of assumptions.Each of the next q lines contains two integers li and ri (1 ≀ li ≀ ri ≀ n) describing the i-th Ann's assumption.OutputPrint q lines, in the i-th of them print the number of subsegments for the i-th Ann's assumption.ExamplesInput4 11 1 1 21 1 1 141 21 31 43 4Output2341Input4 01 2 1 20 0 0 011 4Output10NoteIn the first sample Ann can buy subsegments [1;1], [2;2], [3;3], [2;4] if they fall into the sales segment, because the number of math problems is greater by 1 on them that the number of economics problems. So we should count for each assumption the number of these subsegments that are subsegments of the given segment.Segments [1;1] and [2;2] are subsegments of [1;2].Segments [1;1], [2;2] and [3;3] are subsegments of [1;3].Segments [1;1], [2;2], [3;3], [2;4] are subsegments of [1;4].Segment [3;3] is subsegment of [3;4].
Input4 11 1 1 21 1 1 141 21 31 43 4
Output2341
2 seconds
256 megabytes
['data structures', 'flows', 'hashing', '*2300']
E. Danil and a Part-time Jobtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDanil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.There are two types of tasks: pow v describes a task to switch lights in the subtree of vertex v. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v.Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.InputThe first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree.The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i.The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise.The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks.The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above.OutputFor each task get v print the number of rooms in the subtree of v, in which the light is turned on.ExampleInput41 1 11 0 0 19get 1get 2get 3get 4pow 1get 1get 2get 3get 4Output20012110Note The tree before the task pow 1. The tree after the task pow 1.
Input41 1 11 0 0 19get 1get 2get 3get 4pow 1get 1get 2get 3get 4
Output20012110
2 seconds
256 megabytes
['bitmasks', 'data structures', 'trees', '*2000']
D. Olya and Energy Drinkstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.Formally, her room can be represented as a field of n × m cells, each cell of which is empty or littered with cans.Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.InputThe first line contains three integers n, m and k (1 ≀ n, m, k ≀ 1000) β€” the sizes of the room and Olya's speed.Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.The last line contains four integers x1, y1, x2, y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” the coordinates of the first and the last cells.OutputPrint a single integer β€” the minimum time it will take Olya to get from (x1, y1) to (x2, y2).If it's impossible to get from (x1, y1) to (x2, y2), print -1.ExamplesInput3 4 4....###.....1 1 3 1Output3Input3 4 1....###.....1 1 3 1Output8Input2 2 1.##.1 1 2 2Output-1NoteIn the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.Olya does not recommend drinking energy drinks and generally believes that this is bad.
Input3 4 4....###.....1 1 3 1
Output3
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'shortest paths', '*2100']
C. Slava and tankstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSlava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map.Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n - 1, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.Help Slava to destroy all tanks using as few bombs as possible.InputThe first line contains a single integer n (2 ≀ n ≀ 100 000) β€” the size of the map.OutputIn the first line print m β€” the minimum number of bombs Slava needs to destroy all tanks.In the second line print m integers k1, k2, ..., km. The number ki means that the i-th bomb should be dropped at the cell ki.If there are multiple answers, you can print any of them.ExamplesInput2Output32 1 2 Input3Output42 1 3 2
Input2
Output32 1 2
2 seconds
256 megabytes
['constructive algorithms', '*1600']
B. Nikita and stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?InputThe first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". OutputPrint a single integerΒ β€” the maximum possible size of beautiful string Nikita can get.ExamplesInputabbaOutput4InputbabOutput2NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful.
Inputabba
Output4
2 seconds
256 megabytes
['brute force', 'dp', '*1500']
A. Alex and broken contesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".Names are case sensitive.InputThe only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 β€” the name of the problem.OutputPrint "YES", if problem is from this contest, and "NO" otherwise.ExamplesInputAlex_and_broken_contestOutputNOInputNikitaAndStringOutputYESInputDanil_and_OlyaOutputNO
InputAlex_and_broken_contest
OutputNO
2 seconds
256 megabytes
['implementation', 'strings', '*1100']
B. Divisiblity of Differencestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset. InputFirst line contains three integers n, k and m (2 ≀ k ≀ n ≀ 100 000, 1 ≀ m ≀ 100 000)Β β€” number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers.Second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 109)Β β€” the numbers in the multiset.OutputIf it is not possible to select k numbers in the desired way, output Β«NoΒ» (without the quotes).Otherwise, in the first line of output print Β«YesΒ» (without the quotes). In the second line print k integers b1, b2, ..., bkΒ β€” the selected numbers. If there are multiple possible solutions, print any of them. ExamplesInput3 2 31 8 4OutputYes1 4 Input3 3 31 8 4OutputNoInput4 3 52 7 7 7OutputYes2 7 7
Input3 2 31 8 4
OutputYes1 4
1 second
512 megabytes
['implementation', 'math', 'number theory', '*1300']
A. Trip For Mealtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputWinnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters.For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance.InputFirst line contains an integer n (1 ≀ n ≀ 100)Β β€” number of visits.Second line contains an integer a (1 ≀ a ≀ 100)Β β€” distance between Rabbit's and Owl's houses.Third line contains an integer b (1 ≀ b ≀ 100)Β β€” distance between Rabbit's and Eeyore's houses.Fourth line contains an integer c (1 ≀ c ≀ 100)Β β€” distance between Owl's and Eeyore's houses.OutputOutput one numberΒ β€” minimum distance in meters Winnie must go through to have a meal n times.ExamplesInput3231Output3Input1235Output0NoteIn the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3.In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all.
Input3231
Output3
1 second
512 megabytes
['math', '*900']
F. Royal Questionstime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his n sons-princes marry the brides with as big dowry as possible.In search of candidates, the king asked neighboring kingdoms, and after a while several delegations arrived with m unmarried princesses. Receiving guests, Karl learned that the dowry of the i th princess is wi of golden coins. Although the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride.Knowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince.Help the king to organize the marriage of his sons in the most profitable way for the treasury.InputThe first line contains two integers n, m (2 ≀ n ≀ 200 000, 1 ≀ m ≀ 200 000)Β β€” number of princes and princesses respectively.Each of following m lines contains three integers ai, bi, wi (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ wi ≀ 10 000)Β β€” number of princes, which i-th princess is ready to marry and the value of her dowry.OutputPrint the only integerΒ β€” the maximum number of gold coins that a king can get by playing the right weddings.ExamplesInput2 31 2 51 2 12 1 10Output15Input3 21 2 103 2 20Output30
Input2 31 2 51 2 12 1 10
Output15
1.5 seconds
512 megabytes
['dsu', 'graphs', 'greedy', '*2500']
E. Delivery Clubtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPetya and Vasya got employed as couriers. During the working day they are to deliver packages to n different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate s1, Vasya is at the point with the coordinate s2, and the clients are at the points x1, x2, ..., xn in the order of the required visit.The guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the i-th client is delivered, the one who delivers the package to the (i + 1)-st client is sent to the path (it can be the same person who went to the point xi, or the other). The friend who is not busy in delivering the current package, is standing still.To communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules. InputThe first line contains three integers n, s1, s2 (1 ≀ n ≀ 100 000, 0 ≀ s1, s2 ≀ 109)Β β€” number of points of delivery and starting positions of Petya and Vasya.The second line contains n integers x1, x2, ..., xnΒ β€” customers coordinates (0 ≀ xi ≀ 109), in the order to make a delivery. It is guaranteed, that among the numbers s1, s2, x1, ..., xn there are no two equal.OutputOutput the only integer, minimum possible maximal distance between couriers during delivery.ExamplesInput2 0 105 6Output10Input3 2 13 4 5Output1Input1 4 52Output2NoteIn the first test case the initial distance between the couriers is 10. This value will be the answer, for example, Petya can perform both deliveries, and Vasya will remain at the starting point.In the second test case you can optimally act, for example, like this: Vasya delivers the package to the first customer, Petya to the second and, finally, Vasya delivers the package to the third client. With this order of delivery, the distance between the couriers will never exceed 1.In the third test case only two variants are possible: if the delivery of a single package is carried out by Petya, the maximum distance between them will be 5 - 2 = 3. If Vasya will deliver the package, the maximum distance is 4 - 2 = 2. The latter method is optimal.
Input2 0 105 6
Output10
2 seconds
512 megabytes
['binary search', 'data structures', 'dp', '*2600']
D. High Crytime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputDisclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :)Rick and Morty like to go to the ridge High Cry for crying loudlyΒ β€” there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this ridge: if Rick and Morty begin crying simultaneously from different mountains, their cry would be heard between these mountains up to the height equal the bitwise OR of mountains they've climbed and all the mountains between them. Bitwise OR is a binary operation which is determined the following way. Consider representation of numbers x and y in binary numeric system (probably with leading zeroes) x = xk... x1x0 and y = yk... y1y0. Then z = xΒ |Β y is defined following way: z = zk... z1z0, where zi = 1, if xi = 1 or yi = 1, and zi = 0 otherwise. In the other words, digit of bitwise OR of two numbers equals zero if and only if digits at corresponding positions is both numbers equals zero. For example bitwise OR of numbers 10 = 10102 and 9 = 10012 equals 11 = 10112. In programming languages C/C++/Java/Python this operation is defined as Β«|Β», and in Pascal as Β«orΒ».Help Rick and Morty calculate the number of ways they can select two mountains in such a way that if they start crying from these mountains their cry will be heard above these mountains and all mountains between them. More formally you should find number of pairs l and r (1 ≀ l < r ≀ n) such that bitwise OR of heights of all mountains between l and r (inclusive) is larger than the height of any mountain at this interval.InputThe first line contains integer n (1 ≀ n ≀ 200 000), the number of mountains in the ridge.Second line contains n integers ai (0 ≀ ai ≀ 109), the heights of mountains in order they are located in the ridge.OutputPrint the only integer, the number of ways to choose two different mountains.ExamplesInput53 2 1 6 5Output8Input43 3 3 3Output0NoteIn the first test case all the ways are pairs of mountains with the numbers (numbering from one):(1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)In the second test case there are no such pairs because for any pair of mountains the height of cry from them is 3, and this height is equal to the height of any mountain.
Input53 2 1 6 5
Output8
1 second
512 megabytes
['binary search', 'bitmasks', 'combinatorics', 'data structures', 'divide and conquer', '*2200']
C. National Propertytime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.Some long and uninteresting story was removed...The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds: a ≀ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word; there is a position 1 ≀ j ≀ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has. For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.Note that some words can be equal.InputThe first line contains two integers n and m (2 ≀ n ≀ 100 000, 1 ≀ m ≀ 100 000)Β β€” the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 ≀ li ≀ 100 000, 1 ≀ si, j ≀ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.It is guaranteed that the total length of all words is not greater than 100 000.OutputIn the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).If the required is possible, in the second line print kΒ β€” the number of letters Denis has to capitalize (make large), and in the third line print k distinct integersΒ β€” these letters. Note that you don't need to minimize the value k.You can print the letters in any order. If there are multiple answers, print any of them.ExamplesInput4 31 21 13 1 3 22 1 1OutputYes22 3 Input6 52 1 22 1 23 1 2 32 1 52 4 42 4 4OutputYes0Input4 34 3 2 2 13 1 1 33 2 3 32 3 1OutputNoNoteIn the first example after Denis makes letters 2 and 3 large, the sequence looks like the following: 2' 1 1 3' 2' 1 1 The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Input4 31 21 13 1 3 22 1 1
OutputYes22 3
1 second
512 megabytes
['2-sat', 'dfs and similar', 'graphs', 'implementation', '*2100']
B. Sorting the Coinstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. InputThe first line contains single integer n (1 ≀ n ≀ 300 000)Β β€” number of coins that Sasha puts behind Dima.Second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n)Β β€” positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.OutputPrint n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on. ExamplesInput41 3 4 2Output1 2 3 2 1Input86 8 3 4 7 2 1 5Output1 2 2 3 4 3 4 5 1NoteLet's denote as O coin out of circulation, and as X β€” coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Input41 3 4 2
Output1 2 3 2 1
1 second
512 megabytes
['dsu', 'implementation', 'sortings', 'two pointers', '*1500']
A. Classroom Watchtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputEighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system.Since the number n on the board was small, Vova quickly guessed which x could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. Write such a program for Vova.InputThe first line contains integer n (1 ≀ n ≀ 109).OutputIn the first line print one integer kΒ β€” number of different values of x satisfying the condition. In next k lines print these values in ascending order.ExamplesInput21Output115Input20Output0NoteIn the first test case x = 15 there is only one variant: 15 + 1 + 5 = 21.In the second test case there are no such x.
Input21
Output115
1 second
512 megabytes
['brute force', 'math', '*1200']
F. Forbidden Indicestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n lowercase Latin letters. Some indices in this string are marked as forbidden.You want to find a string a such that the value of |a|Β·f(a) is maximum possible, where f(a) is the number of occurences of a in s such that these occurences end in non-forbidden indices. So, for example, if s is aaaa, a is aa and index 3 is forbidden, then f(a) = 2 because there are three occurences of a in s (starting in indices 1, 2 and 3), but one of them (starting in index 2) ends in a forbidden index.Calculate the maximum possible value of |a|Β·f(a) you can get.InputThe first line contains an integer number n (1 ≀ n ≀ 200000) β€” the length of s.The second line contains a string s, consisting of n lowercase Latin letters.The third line contains a string t, consisting of n characters 0 and 1. If i-th character in t is 1, then i is a forbidden index (otherwise i is not forbidden).OutputPrint the maximum possible value of |a|Β·f(a).ExamplesInput5ababa00100Output5Input5ababa00000Output6Input5ababa11111Output0
Input5ababa00100
Output5
2 seconds
256 megabytes
['dsu', 'string suffix structures', 'strings', '*2400']
E. Awards For Contestantstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlexey recently held a programming contest for students from Berland. n students participated in a contest, i-th of them solved ai problems. Now he wants to award some contestants. Alexey can award the students with diplomas of three different degrees. Each student either will receive one diploma of some degree, or won't receive any diplomas at all. Let cntx be the number of students that are awarded with diplomas of degree x (1 ≀ x ≀ 3). The following conditions must hold: For each x (1 ≀ x ≀ 3) cntx > 0; For any two degrees x and y cntx ≀ 2Β·cnty. Of course, there are a lot of ways to distribute the diplomas. Let bi be the degree of diploma i-th student will receive (or  - 1 if i-th student won't receive any diplomas). Also for any x such that 1 ≀ x ≀ 3 let cx be the maximum number of problems solved by a student that receives a diploma of degree x, and dx be the minimum number of problems solved by a student that receives a diploma of degree x. Alexey wants to distribute the diplomas in such a way that: If student i solved more problems than student j, then he has to be awarded not worse than student j (it's impossible that student j receives a diploma and i doesn't receive any, and also it's impossible that both of them receive a diploma, but bj < bi); d1 - c2 is maximum possible; Among all ways that maximize the previous expression, d2 - c3 is maximum possible; Among all ways that correspond to the two previous conditions, d3 - c - 1 is maximum possible, where c - 1 is the maximum number of problems solved by a student that doesn't receive any diploma (or 0 if each student is awarded with some diploma). Help Alexey to find a way to award the contestants!InputThe first line contains one integer number n (3 ≀ n ≀ 3000).The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 5000).OutputOutput n numbers. i-th number must be equal to the degree of diploma i-th contestant will receive (or  - 1 if he doesn't receive any diploma).If there are multiple optimal solutions, print any of them. It is guaranteed that the answer always exists.ExamplesInput41 2 3 4Output3 3 2 1 Input61 4 3 1 1 2Output-1 1 2 -1 -1 3
Input41 2 3 4
Output3 3 2 1
1 second
256 megabytes
['brute force', 'data structures', 'dp', '*2300']
D. Merge Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMerge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows: If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≀ i < r - 1 a[i] ≀ a[i + 1]), then end the function call; Let ; Call mergesort(a, l, mid); Call mergesort(a, mid, r); Merge segments [l, mid) and [mid, r), making the segment [l, r) sorted in non-descending order. The merge algorithm doesn't call any other functions. The array in this problem is 0-indexed, so to sort the whole array, you need to call mergesort(a, 0, n).The number of calls of function mergesort is very important, so Ivan has decided to calculate it while sorting the array. For example, if a = {1, 2, 3, 4}, then there will be 1 call of mergesort β€” mergesort(0, 4), which will check that the array is sorted and then end. If a = {2, 1, 3}, then the number of calls is 3: first of all, you call mergesort(0, 3), which then sets mid = 1 and calls mergesort(0, 1) and mergesort(1, 3), which do not perform any recursive calls because segments (0, 1) and (1, 3) are sorted.Ivan has implemented the program that counts the number of mergesort calls, but now he needs to test it. To do this, he needs to find an array a such that a is a permutation of size n (that is, the number of elements in a is n, and every integer number from [1, n] can be found in this array), and the number of mergesort calls when sorting the array is exactly k.Help Ivan to find an array he wants!InputThe first line contains two numbers n and k (1 ≀ n ≀ 100000, 1 ≀ k ≀ 200000) β€” the size of a desired permutation and the number of mergesort calls required to sort it.OutputIf a permutation of size n such that there will be exactly k calls of mergesort while sorting it doesn't exist, output  - 1. Otherwise output n integer numbers a[0], a[1], ..., a[n - 1] β€” the elements of a permutation that would meet the required conditions. If there are multiple answers, print any of them.ExamplesInput3 3Output2 1 3 Input4 1Output1 2 3 4 Input5 6Output-1
Input3 3
Output2 1 3
2 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', '*1800']
C. Strange Game On Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is playing a strange game.He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows: Initially Ivan's score is 0; In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that ai, j = 1). If there are no 1's in the column, this column is skipped; Ivan will look at the next min(k, n - i + 1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score. Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.InputThe first line contains three integer numbers n, m and k (1 ≀ k ≀ n ≀ 100, 1 ≀ m ≀ 100).Then n lines follow, i-th of them contains m integer numbers β€” the elements of i-th row of matrix a. Each number is either 0 or 1.OutputPrint two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score.ExamplesInput4 3 20 1 01 0 10 1 01 1 1Output4 1Input3 2 11 00 10 0Output2 0NoteIn the first example Ivan will replace the element a1, 2.
Input4 3 20 1 01 0 10 1 01 1 1
Output4 1
1 second
256 megabytes
['greedy', 'two pointers', '*1600']
B. Balanced Substringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.You have to determine the length of the longest balanced substring of s.InputThe first line contains n (1 ≀ n ≀ 100000) β€” the number of characters in s.The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.OutputIf there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.ExamplesInput811010111Output4Input3111Output0NoteIn the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.In the second example it's impossible to find a non-empty balanced substring.
Input811010111
Output4
1 second
256 megabytes
['dp', 'implementation', '*1500']
A. Chorestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuba has to do n chores today. i-th chore takes ai units of time to complete. It is guaranteed that for every the condition ai β‰₯ ai - 1 is met, so the sequence is sorted.Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of ai ().Luba is very responsible, so she has to do all n chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously.InputThe first line contains three integers n, k, xΒ (1 ≀ k ≀ n ≀ 100, 1 ≀ x ≀ 99) β€” the number of chores Luba has to do, the number of chores she can do in x units of time, and the number x itself.The second line contains n integer numbers aiΒ (2 ≀ ai ≀ 100) β€” the time Luba has to spend to do i-th chore.It is guaranteed that , and for each ai β‰₯ ai - 1.OutputPrint one number β€” minimum time Luba needs to do all n chores.ExamplesInput4 2 23 6 7 10Output13Input5 2 1100 100 100 100 100Output302NoteIn the first example the best option would be to do the third and the fourth chore, spending x = 2 time on each instead of a3 and a4, respectively. Then the answer is 3 + 6 + 2 + 2 = 13.In the second example Luba can choose any two chores to spend x time on them instead of ai. So the answer is 100Β·3 + 2Β·1 = 302.
Input4 2 23 6 7 10
Output13
2 seconds
256 megabytes
['implementation', '*800']
E. Restore the Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya had a tree consisting of n vertices numbered with integers from 1 to n. Accidentally he lost his tree. Petya remembers information about k vertices: distances from each of them to each of the n tree vertices.Your task is to restore any tree that satisfies the information that Petya remembers or report that such tree doesn't exist.InputThe first line contains two integers n and k (2 ≀ n ≀ 30 000, 1 ≀ k ≀ min(200, n)) β€” the number of vertices in the tree and the number of vertices about which Petya remembers distance information.The following k lines contain remembered information. The i-th line contains n integers di, 1, di, 2, ..., di, n (0 ≀ di, j ≀ n - 1), where di, j β€” the distance to j-th vertex from the i-th vertex that Petya remembers.OutputIf there are no suitable trees, print -1.In the other case, print n - 1 lines: each line should contain two vertices connected by edge in the required tree. You can print edges and vertices in an edge in any order. The tree vertices are enumerated from 1 to n.If there are many solutions print any of them.ExamplesInput5 20 1 2 3 22 1 0 1 2Output2 13 24 35 2Input3 11 2 1Output-1NotePicture for the first sample:
Input5 20 1 2 3 22 1 0 1 2
Output2 13 24 35 2
3 seconds
256 megabytes
['graphs', 'greedy', 'trees', '*2900']
F. Pathstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Let's build a graph on vertices 1, 2, ..., n in such a way that there is an edge between vertices u and v if and only if . Let d(u, v) be the shortest distance between u and v, or 0 if there is no path between them. Compute the sum of values d(u, v) over all 1 ≀ u < v ≀ n.The gcd (greatest common divisor) of two positive integers is the maximum positive integer that divides both of the integers.InputSingle integer n (1 ≀ n ≀ 107).OutputPrint the sum of d(u, v) over all 1 ≀ u < v ≀ n.ExamplesInput6Output8Input10Output44NoteAll shortest paths in the first example: There are no paths between other pairs of vertices.The total distance is 2 + 1 + 1 + 2 + 1 + 1 = 8.
Input6
Output8
4 seconds
512 megabytes
['data structures', 'number theory', '*2700']
E. Points, Lines and Ready-made Titlestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 109 + 7.InputThe first line contains single integer n (1 ≀ n ≀ 105)Β β€” the number of points.n lines follow. The (i + 1)-th of these lines contains two integers xi, yi ( - 109 ≀ xi, yi ≀ 109)Β β€” coordinates of the i-th point.It is guaranteed that all points are distinct.OutputPrint the number of possible distinct pictures modulo 109 + 7.ExamplesInput41 11 22 12 2Output16Input2-1 -10 1Output9NoteIn the first example there are two vertical and two horizontal lines passing through the points. You can get pictures with any subset of these lines. For example, you can get the picture containing all four lines in two ways (each segment represents a line containing it). The first way: The second way: In the second example you can work with two points independently. The number of pictures is 32 = 9.
Input41 11 22 12 2
Output16
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'trees', '*2300']
D. Something with XOR Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Jury has hidden a permutation p of integers from 0 to n - 1. You know only the length n. Remind that in permutation all integers are distinct.Let b be the inverse permutation for p, i.e. pbi = i for all i. The only thing you can do is to ask xor of elements pi and bj, printing two indices i and j (not necessarily distinct). As a result of the query with indices i and j you'll get the value , where denotes the xor operation. You can find the description of xor operation in notes.Note that some permutations can remain indistinguishable from the hidden one, even if you make all possible n2 queries. You have to compute the number of permutations indistinguishable from the hidden one, and print one of such permutations, making no more than 2n queries.The hidden permutation does not depend on your queries.InputThe first line contains single integer n (1 ≀ n ≀ 5000) β€” the length of the hidden permutation. You should read this integer first.OutputWhen your program is ready to print the answer, print three lines.In the first line print "!".In the second line print single integer answers_cntΒ β€” the number of permutations indistinguishable from the hidden one, including the hidden one. In the third line print n integers p0, p1, ..., pn - 1 (0 ≀ pi < n, all pi should be distinct)Β β€” one of the permutations indistinguishable from the hidden one.Your program should terminate after printing the answer.InteractionTo ask about xor of two elements, print a string "? i j", where i and j β€” are integers from 0 to n - 1 β€” the index of the permutation element and the index of the inverse permutation element you want to know the xor-sum for. After that print a line break and make flush operation.After printing the query your program should read single integerΒ β€” the value of .For a permutation of length n your program should make no more than 2n queries about xor-sum. Note that printing answer doesn't count as a query. Note that you can't ask more than 2n questions. If you ask more than 2n questions or at least one incorrect question, your solution will get "Wrong answer".If at some moment your program reads -1 as an answer, it should immediately exit (for example, by calling exit(0)). You will get "Wrong answer" in this case, it means that you asked more than 2n questions, or asked an invalid question. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.Your solution will get "Idleness Limit Exceeded", if you don't print anything or forget to flush the output, including for the final answer .To flush you can use (just after printing line break): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; For other languages see the documentation. HackingFor hacking use the following format:np0 p1 ... pn - 1Contestant programs will not be able to see this input.ExamplesInput3003232Output? 0 0? 1 1? 1 2? 0 2? 2 1? 2 0!10 1 2Input423202320Output? 0 1? 1 2? 2 3? 3 3? 3 2? 2 1? 1 0? 0 0!23 1 2 0Notexor operation, or bitwise exclusive OR, is an operation performed over two integers, in which the i-th digit in binary representation of the result is equal to 1 if and only if exactly one of the two integers has the i-th digit in binary representation equal to 1. For more information, see here.In the first example p = [0, 1, 2], thus b = [0, 1, 2], the values are correct for the given i, j. There are no other permutations that give the same answers for the given queries.The answers for the queries are: , , , , , . In the second example p = [3, 1, 2, 0], and b = [3, 1, 2, 0], the values match for all pairs i, j. But there is one more suitable permutation p = [0, 2, 1, 3], b = [0, 2, 1, 3] that matches all n2 possible queries as well. All other permutations do not match even the shown queries.
Input3003232
Output? 0 0? 1 1? 1 2? 0 2? 2 1? 2 0!10 1 2
2 seconds
256 megabytes
['brute force', 'interactive', 'probabilities', '*2000']
C. Maximum splittingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.InputThe first line contains single integer q (1 ≀ q ≀ 105)Β β€” the number of queries.q lines follow. The (i + 1)-th line contains single integer ni (1 ≀ ni ≀ 109)Β β€” the i-th query.OutputFor each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.ExamplesInput112Output3Input268Output12Input3123Output-1-1-1Note12 = 4 + 4 + 4 = 4 + 8 = 6 + 6 = 12, but the first splitting has the maximum possible number of summands.8 = 4 + 4, 6 can't be split into several composite summands.1, 2, 3 are less than any composite number, so they do not have valid splittings.
Input112
Output3
2 seconds
256 megabytes
['dp', 'greedy', 'math', 'number theory', '*1300']
B. Maximum of Maximums of Minimumstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀  105) β€” the size of the array a and the number of subsegments you have to split the array to.The second line contains n integers a1,  a2,  ...,  an ( - 109  ≀  ai ≀  109).OutputPrint single integer β€” the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.ExamplesInput5 21 2 3 4 5Output5Input5 1-4 -5 -3 -2 -1Output-5NoteA subsegment [l,  r] (l ≀ r) of array a is the sequence al,  al + 1,  ...,  ar.Splitting of array a of n elements into k subsegments [l1, r1], [l2, r2], ..., [lk, rk] (l1 = 1, rk = n, li = ri - 1 + 1 for all i > 1) is k sequences (al1, ..., ar1), ..., (alk, ..., ark).In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.
Input5 21 2 3 4 5
Output5
1 second
256 megabytes
['greedy', '*1200']
A. Search for Pretty Integerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two lists of non-zero digits.Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?InputThe first line contains two integers n and m (1 ≀ n, m ≀ 9) β€” the lengths of the first and the second lists, respectively.The second line contains n distinct digits a1, a2, ..., an (1 ≀ ai ≀ 9) β€” the elements of the first list.The third line contains m distinct digits b1, b2, ..., bm (1 ≀ bi ≀ 9) β€” the elements of the second list.OutputPrint the smallest pretty integer.ExamplesInput2 34 25 7 6Output25Input8 81 2 3 4 5 6 7 88 7 6 5 4 3 2 1Output1NoteIn the first example 25, 46, 24567 are pretty, as well as many other integers. The smallest among them is 25. 42 and 24 are not pretty because they don't have digits from the second list.In the second example all integers that have at least one digit different from 9 are pretty. It's obvious that the smallest among them is 1, because it's the smallest positive integer.
Input2 34 25 7 6
Output25
1 second
256 megabytes
['brute force', 'implementation', '*900']
E. The Untended Antiquitytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAdieu l'ami.Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.The space is represented by a rectangular grid of n × m cells, arranged into n rows and m columns. The c-th cell in the r-th row is denoted by (r, c).Oshino places and removes barriers around rectangular areas of cells. Specifically, an action denoted by "1 r1 c1 r2 c2" means Oshino's placing barriers around a rectangle with two corners being (r1, c1) and (r2, c2) and sides parallel to squares sides. Similarly, "2 r1 c1 r2 c2" means Oshino's removing barriers around the rectangle. Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the n × m area.Sometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. "3 r1 c1 r2 c2" means that Koyomi tries to walk from (r1, c1) to (r2, c2) without crossing barriers.And you're here to tell Koyomi the feasibility of each of his attempts.InputThe first line of input contains three space-separated integers n, m and q (1 ≀ n, m ≀ 2 500, 1 ≀ q ≀ 100 000) β€” the number of rows and columns in the grid, and the total number of Oshino and Koyomi's actions, respectively.The following q lines each describes an action, containing five space-separated integers t, r1, c1, r2, c2 (1 ≀ t ≀ 3, 1 ≀ r1, r2 ≀ n, 1 ≀ c1, c2 ≀ m) β€” the type and two coordinates of an action. Additionally, the following holds depending on the value of t: If t = 1: 2 ≀ r1 ≀ r2 ≀ n - 1, 2 ≀ c1 ≀ c2 ≀ m - 1; If t = 2: 2 ≀ r1 ≀ r2 ≀ n - 1, 2 ≀ c1 ≀ c2 ≀ m - 1, the specified group of barriers exist on the ground before the removal. If t = 3: no extra restrictions. OutputFor each of Koyomi's attempts (actions with t = 3), output one line β€” containing "Yes" (without quotes) if it's feasible, and "No" (without quotes) otherwise.ExamplesInput5 6 51 2 2 4 51 3 3 3 33 4 4 1 12 2 2 4 53 1 1 4 4OutputNoYesInput2500 2500 81 549 1279 1263 21891 303 795 1888 24321 2227 622 2418 11613 771 2492 1335 14331 2017 2100 2408 21603 48 60 798 7291 347 708 1868 7923 1940 2080 377 1546OutputNoYesNoNoteFor the first example, the situations of Koyomi's actions are illustrated below.
Input5 6 51 2 2 4 51 3 3 3 33 4 4 1 12 2 2 4 53 1 1 4 4
OutputNoYes
2 seconds
512 megabytes
['data structures', 'hashing', '*2400']
D. The Overdosing Ubiquitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe fundamental prerequisite for justice is not to be correct, but to be strong. That's why justice is always the victor.The Cinderswarm Bee. Koyomi knows it.The bees, according to their nature, live in a tree. To be more specific, a complete binary tree with n nodes numbered from 1 to n. The node numbered 1 is the root, and the parent of the i-th (2 ≀ i ≀ n) node is . Note that, however, all edges in the tree are undirected.Koyomi adds m extra undirected edges to the tree, creating more complication to trick the bees. And you're here to count the number of simple paths in the resulting graph, modulo 109 + 7. A simple path is an alternating sequence of adjacent nodes and undirected edges, which begins and ends with nodes and does not contain any node more than once. Do note that a single node is also considered a valid simple path under this definition. Please refer to the examples and notes below for instances.InputThe first line of input contains two space-separated integers n and m (1 ≀ n ≀ 109, 0 ≀ m ≀ 4) β€” the number of nodes in the tree and the number of extra edges respectively.The following m lines each contains two space-separated integers u and v (1 ≀ u, v ≀ n, u ≠ v) β€” describing an undirected extra edge whose endpoints are u and v.Note that there may be multiple edges between nodes in the resulting graph.OutputOutput one integer β€” the number of simple paths in the resulting graph, modulo 109 + 7.ExamplesInput3 0Output9Input3 12 3Output15Input2 41 22 11 22 1Output12NoteIn the first example, the paths are: (1); (2); (3); (1, 2); (2, 1); (1, 3); (3, 1); (2, 1, 3); (3, 1, 2). (For the sake of clarity, the edges between nodes are omitted since there are no multiple edges in this case.)In the second example, the paths are: (1); (1, 2); (1, 2, 3); (1, 3); (1, 3, 2); and similarly for paths starting with 2 and 3. (5 × 3 = 15 paths in total.)In the third example, the paths are: (1); (2); any undirected edge connecting the two nodes travelled in either direction. (2 + 5 × 2 = 12 paths in total.)
Input3 0
Output9
1 second
256 megabytes
['brute force', 'dfs and similar', 'graphs', '*2800']
C. The Intriguing Obsessiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputβ€” This is not playing but duty as allies of justice, Nii-chan!β€” Not allies but justice itself, Onii-chan!With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire SistersΒ β€” Karen and TsukihiΒ β€” is heading for somewhere they've never reachedΒ β€” water-surrounded islands!There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of a, b and c distinct islands respectively.Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length 1. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is at least 3, apparently in order to prevent oddities from spreading quickly inside a cluster.The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo 998 244 353. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other.InputThe first and only line of input contains three space-separated integers a, b and c (1 ≀ a, b, c ≀ 5 000)Β β€” the number of islands in the red, blue and purple clusters, respectively.OutputOutput one line containing an integerΒ β€” the number of different ways to build bridges, modulo 998 244 353.ExamplesInput1 1 1Output8Input1 2 2Output63Input1 3 5Output3264Input6 2 9Output813023575NoteIn the first example, there are 3 bridges that can possibly be built, and no setup of bridges violates the restrictions. Thus the answer is 23 = 8.In the second example, the upper two structures in the figure below are instances of valid ones, while the lower two are invalid due to the blue and purple clusters, respectively.
Input1 1 1
Output8
1 second
256 megabytes
['combinatorics', 'dp', 'math', '*1800']
B. The Eternal Immortalitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEven if the world is full of counterfeits, I still regard it as wonderful.Pile up herbs and incense, and arise again from the flames and ashes of its predecessorΒ β€” as is known to many, the phoenix does it like this.The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes the factorial of integer a, that is, a! = 1 × 2 × ... × a. Specifically, 0! = 1.Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of b! years, that is, . Note that when b β‰₯ a this value is always integer.As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge.InputThe first and only line of input contains two space-separated integers a and b (0 ≀ a ≀ b ≀ 1018).OutputOutput one line containing a single decimal digitΒ β€” the last digit of the value that interests Koyomi.ExamplesInput2 4Output2Input0 10Output0Input107 109Output2NoteIn the first example, the last digit of is 2;In the second example, the last digit of is 0;In the third example, the last digit of is 2.
Input2 4
Output2
1 second
256 megabytes
['math', '*1100']
A. The Artful Expedienttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRock... Paper!After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted by x1, x2, ..., xn and y1, y2, ..., yn respectively. They reveal their sequences, and repeat until all of 2n integers become distinct, which is the only final state to be kept and considered.Then they count the number of ordered pairs (i, j) (1 ≀ i, j ≀ n) such that the value xi xor yj equals to one of the 2n integers. Here xor means the bitwise exclusive or operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.InputThe first line of input contains a positive integer n (1 ≀ n ≀ 2 000) β€” the length of both sequences.The second line contains n space-separated integers x1, x2, ..., xn (1 ≀ xi ≀ 2Β·106) β€” the integers finally chosen by Koyomi.The third line contains n space-separated integers y1, y2, ..., yn (1 ≀ yi ≀ 2Β·106) β€” the integers finally chosen by Karen.Input guarantees that the given 2n integers are pairwise distinct, that is, no pair (i, j) (1 ≀ i, j ≀ n) exists such that one of the following holds: xi = yj; i ≠ j and xi = xj; i ≠ j and yi = yj.OutputOutput one line β€” the name of the winner, that is, "Koyomi" or "Karen" (without quotes). Please be aware of the capitalization.ExamplesInput31 2 34 5 6OutputKarenInput52 4 6 8 109 7 5 3 1OutputKarenNoteIn the first example, there are 6 pairs satisfying the constraint: (1, 1), (1, 2), (2, 1), (2, 3), (3, 2) and (3, 3). Thus, Karen wins since 6 is an even number.In the second example, there are 16 such pairs, and Karen wins again.
Input31 2 34 5 6
OutputKaren
1 second
256 megabytes
['brute force', 'implementation', '*1100']
G. El Toll Cavestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe prehistoric caves of El Toll are located in MoiΓ  (Barcelona). You have heard that there is a treasure hidden in one of n possible spots in the caves. You assume that each of the spots has probability 1 / n to contain a treasure.You cannot get into the caves yourself, so you have constructed a robot that can search the caves for treasure. Each day you can instruct the robot to visit exactly k distinct spots in the caves. If none of these spots contain treasure, then the robot will obviously return with empty hands. However, the caves are dark, and the robot may miss the treasure even when visiting the right spot. Formally, if one of the visited spots does contain a treasure, the robot will obtain it with probability 1 / 2, otherwise it will return empty. Each time the robot searches the spot with the treasure, his success probability is independent of all previous tries (that is, the probability to miss the treasure after searching the right spot x times is 1 / 2x).What is the expected number of days it will take to obtain the treasure if you choose optimal scheduling for the robot? Output the answer as a rational number modulo 109 + 7. Formally, let the answer be an irreducible fraction P / Q, then you have to output . It is guaranteed that Q is not divisible by 109 + 7.InputThe first line contains the number of test cases T (1 ≀ T ≀ 1000).Each of the next T lines contains two integers n and k (1 ≀ k ≀ n ≀ 5Β·108).OutputFor each test case output the answer in a separate line.ExampleInput31 12 13 2Output2500000007777777786NoteIn the first case the robot will repeatedly search in the only spot. The expected number of days in this case is 2. Note that in spite of the fact that we know the treasure spot from the start, the robot still has to search there until he succesfully recovers the treasure.In the second case the answer can be shown to be equal to 7 / 2 if we search the two spots alternatively. In the third case the answer is 25 / 9.
Input31 12 13 2
Output2500000007777777786
2 seconds
256 megabytes
['math', '*3300']
F. Yet Another Minimization Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.InputThe first line contains two integers n and k (2 ≀ n ≀ 105, 2 ≀ k ≀ min (n, 20)) Β β€” the length of the array and the number of segments you need to split the array into.The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n)Β β€” the elements of the array.OutputPrint single integer: the minimum possible total cost of resulting subsegments.ExamplesInput7 31 1 3 3 3 2 1Output1Input10 21 2 1 2 1 2 1 2 1 2Output8Input13 31 2 2 2 1 2 1 1 1 2 2 1 1Output9NoteIn the first example it's optimal to split the sequence into the following three subsegments: [1], [1, 3], [3, 3, 2, 1]. The costs are 0, 0 and 1, thus the answer is 1.In the second example it's optimal to split the sequence in two equal halves. The cost for each half is 4.In the third example it's optimal to split the sequence in the following way: [1, 2, 2, 2, 1], [2, 1, 1, 1, 2], [2, 1, 1]. The costs are 4, 4, 1.
Input7 31 1 3 3 3 2 1
Output1
2 seconds
256 megabytes
['divide and conquer', 'dp', '*2500']
E. Policeman and a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (a connected non-oriented graph without cycles) with vertices numbered from 1 to n, and the length of the i-th edge is wi. In the vertex s there is a policeman, in the vertices x1, x2, ..., xm (xj ≠ s) m criminals are located.The policeman can walk along the edges with speed 1, the criminals can move with arbitrary large speed. If a criminal at some moment is at the same point as the policeman, he instantly gets caught by the policeman. Determine the time needed for the policeman to catch all criminals, assuming everybody behaves optimally (i.e. the criminals maximize that time, the policeman minimizes that time). Everybody knows positions of everybody else at any moment of time.InputThe first line contains single integer n (1 ≀ n ≀ 50)Β β€” the number of vertices in the tree. The next n - 1 lines contain three integers each: ui, vi, wi (1 ≀ ui, vi ≀ n, 1 ≀ wi ≀ 50) denoting edges and their lengths. It is guaranteed that the given graph is a tree.The next line contains single integer s (1 ≀ s ≀ n)Β β€” the number of vertex where the policeman starts.The next line contains single integer m (1 ≀ m ≀ 50)Β β€” the number of criminals. The next line contains m integers x1, x2, ..., xm (1 ≀ xj ≀ n, xj ≠ s)Β β€” the number of vertices where the criminals are located. xj are not necessarily distinct.OutputIf the policeman can't catch criminals, print single line "Terrorists win" (without quotes).Otherwise, print single integerΒ β€” the time needed to catch all criminals.ExamplesInput41 2 21 3 11 4 1243 1 4 1Output8Input61 2 32 3 53 4 13 5 42 6 3231 3 5Output21NoteIn the first example one of the optimal scenarios is the following. The criminal number 2 moves to vertex 3, the criminal 4Β β€” to vertex 4. The policeman goes to vertex 4 and catches two criminals. After that the criminal number 1 moves to the vertex 2. The policeman goes to vertex 3 and catches criminal 2, then goes to the vertex 2 and catches the remaining criminal.
Input41 2 21 3 11 4 1243 1 4 1
Output8
2 seconds
256 megabytes
['dp', 'graphs', 'trees', '*2700']
D. Huge Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.InputThe first line contains single integer n (1 ≀ n ≀ 100)Β β€” the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≀ |si| ≀ 100), one per line. The total length of strings is not greater than 100.The next line contains single integer m (1 ≀ m ≀ 100)Β β€” the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≀ ai, bi ≀ n + i - 1)Β β€” the number of strings that are concatenated to form sn + i.OutputPrint m lines, each should contain one integerΒ β€” the answer to the question after the corresponding operation.ExampleInput5011010111111031 26 54 4Output120NoteOn the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.On the second operation the string "01100" is created. Now all strings of length k = 2 are present.On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.
Input5011010111111031 26 54 4
Output120
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'implementation', 'strings', '*2200']
C. Qualification Roundstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSnark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.Determine if Snark and Philip can make an interesting problemset!InputThe first line contains two integers n, k (1 ≀ n ≀ 105, 1 ≀ k ≀ 4)Β β€” the number of problems and the number of experienced teams.Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.OutputPrint "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise.You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").ExamplesInput5 31 0 11 1 01 0 01 0 01 0 0OutputNOInput3 21 01 10 1OutputYESNoteIn the first example you can't make any interesting problemset, because the first team knows all problems.In the second example you can choose the first and the third problems.
Input5 31 0 11 1 01 0 01 0 01 0 0
OutputNO
2 seconds
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'dp', '*1500']
B. Race Against Timetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHave you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.The entire universe turned into an enormous clock face with three handsΒ β€” hour, minute, and second. Time froze, and clocks now show the time h hours, m minutes, s seconds.Last time Misha talked with the coordinator at t1 o'clock, so now he stands on the number t1 on the clock face. The contest should be ready by t2 o'clock. In the terms of paradox it means that Misha has to go to number t2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction.Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way).Given the hands' positions, t1, and t2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from t1 to t2 by the clock face.InputFive integers h, m, s, t1, t2 (1 ≀ h ≀ 12, 0 ≀ m, s ≀ 59, 1 ≀ t1, t2 ≀ 12, t1 ≠ t2).Misha's position and the target time do not coincide with the position of any hand.OutputPrint "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise.You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").ExamplesInput12 30 45 3 11OutputNOInput12 0 1 12 1OutputYESInput3 47 0 4 9OutputYESNoteThe three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the pictures are not exact, but are close to the exact and the answer is the same.
Input12 30 45 3 11
OutputNO
2 seconds
256 megabytes
['implementation', '*1400']
A. Bark to Unlocktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.InputThe first line contains two lowercase English lettersΒ β€” the password on the phone.The second line contains single integer n (1 ≀ n ≀ 100)Β β€” the number of words Kashtanka knows.The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct.OutputPrint "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise.You can print each letter in arbitrary case (upper or lower).ExamplesInputya4ahoytohaOutputYESInputhp2httpOutputNOInputah1haOutputYESNoteIn the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES".In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring.In the third example the string "hahahaha" contains "ah" as a substring.
Inputya4ahoytoha
OutputYES
2 seconds
256 megabytes
['brute force', 'implementation', 'strings', '*900']
A. Between the Officestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last n days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last n days, or not.InputThe first line of input contains single integer n (2 ≀ n ≀ 100)Β β€” the number of days.The second line contains a string of length n consisting of only capital 'S' and 'F' letters. If the i-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence.OutputPrint "YES" if you flew more times from Seattle to San Francisco, and "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInput4FSSFOutputNOInput2SFOutputYESInput10FFFFFFFFFFOutputNOInput10SSFFSFFSFFOutputYESNoteIn the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is "NO".In the second example you just flew from Seattle to San Francisco, so the answer is "YES".In the third example you stayed the whole period in San Francisco, so the answer is "NO".In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of Ο€ in binary representation. Not very useful information though.
Input4FSSF
OutputNO
2 seconds
256 megabytes
['implementation', '*800']
G. Flowers and Chocolatetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's Piegirl's birthday soon, and Pieguy has decided to buy her a bouquet of flowers and a basket of chocolates.The flower shop has F different types of flowers available. The i-th type of flower always has exactly pi petals. Pieguy has decided to buy a bouquet consisting of exactly N flowers. He may buy the same type of flower multiple times. The N flowers are then arranged into a bouquet. The position of the flowers within a bouquet matters. You can think of a bouquet as an ordered list of flower types.The chocolate shop sells chocolates in boxes. There are B different types of boxes available. The i-th type of box contains ci pieces of chocolate. Pieguy can buy any number of boxes, and can buy the same type of box multiple times. He will then place these boxes into a basket. The position of the boxes within the basket matters. You can think of the basket as an ordered list of box types.Pieguy knows that Piegirl likes to pluck a petal from a flower before eating each piece of chocolate. He would like to ensure that she eats the last piece of chocolate from the last box just after plucking the last petal from the last flower. That is, the total number of petals on all the flowers in the bouquet should equal the total number of pieces of chocolate in all the boxes in the basket.How many different bouquet+basket combinations can Pieguy buy? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.InputThe first line of input will contain integers F, B, and N (1 ≀ F ≀ 10, 1 ≀ B ≀ 100, 1 ≀ N ≀ 1018), the number of types of flowers, the number of types of boxes, and the number of flowers that must go into the bouquet, respectively.The second line of input will contain F integers p1, p2, ..., pF (1 ≀ pi ≀ 109), the numbers of petals on each of the flower types.The third line of input will contain B integers c1, c2, ..., cB (1 ≀ ci ≀ 250), the number of pieces of chocolate in each of the box types.OutputPrint the number of bouquet+basket combinations Pieguy can buy, modulo 1000000007 = 109 + 7.ExamplesInput2 3 33 510 3 7Output17Input6 5 109 3 3 4 9 99 9 1 6 4Output31415926NoteIn the first example, there is 1 way to make a bouquet with 9 petals (3 + 3 + 3), and 1 way to make a basket with 9 pieces of chocolate (3 + 3 + 3), for 1 possible combination. There are 3 ways to make a bouquet with 13 petals (3 + 5 + 5, 5 + 3 + 5, 5 + 5 + 3), and 5 ways to make a basket with 13 pieces of chocolate (3 + 10, 10 + 3, 3 + 3 + 7, 3 + 7 + 3, 7 + 3 + 3), for 15 more combinations. Finally there is 1 way to make a bouquet with 15 petals (5 + 5 + 5) and 1 way to make a basket with 15 pieces of chocolate (3 + 3 + 3 + 3 + 3), for 1 more combination.Note that it is possible for multiple types of flowers to have the same number of petals. Such types are still considered different. Similarly different types of boxes may contain the same number of pieces of chocolate, but are still considered different.
Input2 3 33 510 3 7
Output17
2 seconds
256 megabytes
['combinatorics', 'math', 'matrices', '*3300']
F. Egg Roulettetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe game of Egg Roulette is played between two players. Initially 2R raw eggs and 2C cooked eggs are placed randomly into a carton. The shells are left on so there is no way to distinguish a raw egg from a cooked egg. One at a time, a player will select an egg, and then smash the egg on his/her forehead. If the egg was cooked, not much happens, but if the egg was raw, it will make quite the mess. This continues until one player has broken R raw eggs, at which point that player is declared the loser and the other player wins.The order in which players take turns can be described as a string of 'A' and 'B' characters, where the i-th character tells which player should choose the i-th egg. Traditionally, players take turns going one after the other. That is, they follow the ordering "ABABAB...". This isn't very fair though, because the second player will win more often than the first. We'd like you to find a better ordering for the players to take their turns. Let's define the unfairness of an ordering as the absolute difference between the first player's win probability and the second player's win probability. We're interested in orderings that minimize the unfairness. We only consider an ordering valid if it contains the same number of 'A's as 'B's.You will also be given a string S of length 2(R + C) containing only 'A', 'B', and '?' characters. An ordering is said to match S if it only differs from S in positions where S contains a '?'. Of the valid orderings that minimize unfairness, how many match S?InputThe first line of input will contain integers R and C (1 ≀ R, C ≀ 20, R + C ≀ 30).The second line of input will contain the string S of length 2(R + C) consisting only of characters 'A', 'B', '?'.OutputPrint the number of valid orderings that minimize unfairness and match S.ExamplesInput1 1??BBOutput0Input2 4?BA??B??A???Output1Input4 14????A??BB?????????????AB????????????Output314NoteIn the first test case, the minimum unfairness is 0, and the orderings that achieve it are "ABBA" and "BAAB", neither of which match S. Note that an ordering such as "ABBB" would also have an unfairness of 0, but is invalid because it does not contain the same number of 'A's as 'B's.In the second example, the only matching ordering is "BBAAABABABBA".
Input1 1??BB
Output0
3 seconds
256 megabytes
['bitmasks', 'brute force', 'divide and conquer', 'math', 'meet-in-the-middle', '*3300']
E. Hex Dyslexiatime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCopying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string, nor the length of the string, but may have permuted the digits arbitrarily. For example, if the original string was 0abc they may have changed it to a0cb or 0bca, but not abc or 0abb.Unfortunately you don't have access to the original string nor the copied string, but you do know the length of the strings and their numerical absolute difference. You will be given this difference as a hexadecimal string S, which has been zero-extended to be equal in length to the original and copied strings. Determine the smallest possible numerical value of the original string.InputInput will contain a hexadecimal string S consisting only of digits 0 to 9 and lowercase English letters from a to f, with length at most 14. At least one of the characters is non-zero.OutputIf it is not possible, print "NO" (without quotes).Otherwise, print the lowercase hexadecimal string corresponding to the smallest possible numerical value, including any necessary leading zeros for the length to be correct.ExamplesInputf1eOutputNOInput0f1eOutput00f1Input12d2cOutput00314NoteThe numerical value of a hexadecimal string is computed by multiplying each digit by successive powers of 16, starting with the rightmost digit, which is multiplied by 160. Hexadecimal digits representing values greater than 9 are represented by letters: a = 10, b = 11, c = 12, d = 13, e = 14, f = 15.For example, the numerical value of 0f1e is 0Β·163 + 15Β·162 + 1Β·161 + 14Β·160 = 3870, the numerical value of 00f1 is 0Β·163 + 0Β·162 + 15Β·161 + 1Β·160 = 241, and the numerical value of 100f is 1Β·163 + 0Β·162 + 0Β·161 + 15Β·160 = 4111. Since 3870 + 241 = 4111 and 00f1 is a permutation of 100f, 00f1 is a valid answer to the second test case.
Inputf1e
OutputNO
3 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'graphs', '*3300']
D. Buy Low Sell Hightime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.InputInput begins with an integer N (2 ≀ N ≀ 3Β·105), the number of days.Following this is a line with exactly N integers p1, p2, ..., pN (1 ≀ pi ≀ 106). The price of one share of stock on the i-th day is given by pi.OutputPrint the maximum amount of money you can end up with at the end of N days.ExamplesInput910 5 4 7 9 12 6 2 10Output20Input203 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4Output41NoteIn the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is  - 5 - 4 + 9 + 12 - 2 + 10 = 20.
Input910 5 4 7 9 12 6 2 10
Output20
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*2400']
C. Gotta Go Fasttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're trying to set the record on your favorite video game. The game consists of N levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the i-th level in either Fi seconds or Si seconds, where Fi < Si, and there's a Pi percent chance of completing it in Fi seconds. After completing a level, you may decide to either continue the game and play the next level, or reset the game and start again from the first level. Both the decision and the action are instant.Your goal is to complete all the levels sequentially in at most R total seconds. You want to minimize the expected amount of time playing before achieving that goal. If you continue and reset optimally, how much total time can you expect to spend playing?InputThe first line of input contains integers N and R , the number of levels and number of seconds you want to complete the game in, respectively. N lines follow. The ith such line contains integers Fi, Si, Pi (1 ≀ Fi < Si ≀ 100, 80 ≀ Pi ≀ 99), the fast time for level i, the slow time for level i, and the probability (as a percentage) of completing level i with the fast time.OutputPrint the total expected time. Your answer must be correct within an absolute or relative error of 10 - 9.Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if .ExamplesInput1 82 8 81Output3.14Input2 3020 30 803 9 85Output31.4Input4 31963 79 8979 97 9175 87 8875 90 83Output314.159265358NoteIn the first example, you never need to reset. There's an 81% chance of completing the level in 2 seconds and a 19% chance of needing 8 seconds, both of which are within the goal time. The expected time is 0.81Β·2 + 0.19Β·8 = 3.14.In the second example, you should reset after the first level if you complete it slowly. On average it will take 0.25 slow attempts before your first fast attempt. Then it doesn't matter whether you complete the second level fast or slow. The expected time is 0.25Β·30 + 20 + 0.85Β·3 + 0.15Β·9 = 31.4.
Input1 82 8 81
Output3.14
2 seconds
256 megabytes
['binary search', 'dp', '*2400']
B. Ordering Pizzatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?InputThe first line of input will contain integers N and S (1 ≀ N ≀ 105, 1 ≀ S ≀ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow.The i-th such line contains integers si, ai, and bi (1 ≀ si ≀ 105, 1 ≀ ai ≀ 105, 1 ≀ bi ≀ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.OutputPrint the maximum total happiness that can be achieved.ExamplesInput3 123 5 74 6 75 9 5Output84Input6 107 4 75 8 812 5 86 11 63 3 75 9 6Output314NoteIn the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3Β·5 + 4Β·6 + 5Β·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3Β·7 + 4Β·7 + 5Β·5 = 74.
Input3 123 5 74 6 75 9 5
Output84
2 seconds
256 megabytes
['binary search', 'sortings', 'ternary search', '*1900']
A. Save the problem!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAttention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.People don't use cash as often as they used to. Having a credit card solves some of the hassles of cash, such as having to receive change when you can't form the exact amount of money needed to purchase an item. Typically cashiers will give you as few coins as possible in change, but they don't have to. For example, if your change is 30 cents, a cashier could give you a 5 cent piece and a 25 cent piece, or they could give you three 10 cent pieces, or ten 1 cent pieces, two 5 cent pieces, and one 10 cent piece. Altogether there are 18 different ways to make 30 cents using only 1 cent pieces, 5 cent pieces, 10 cent pieces, and 25 cent pieces. Two ways are considered different if they contain a different number of at least one type of coin. Given the denominations of the coins and an amount of change to be made, how many different ways are there to make change?As we mentioned before, we lost all the test cases for this problem, so we're actually going to give you the number of ways, and want you to produce a test case for which the number of ways is the given number. There could be many ways to achieve this (we guarantee there's always at least one), so you can print any, as long as it meets the constraints described below.InputInput will consist of a single integer A (1 ≀ A ≀ 105), the desired number of ways.OutputIn the first line print integers N and M (1 ≀ N ≀ 106, 1 ≀ M ≀ 10), the amount of change to be made, and the number of denominations, respectively.Then print M integers D1, D2, ..., DM (1 ≀ Di ≀ 106), the denominations of the coins. All denominations must be distinct: for any i ≠ j we must have Di ≠ Dj.If there are multiple tests, print any of them. You can print denominations in atbitrary order.ExamplesInput18Output30 41 5 10 25Input3Output20 25 2Input314Output183 46 5 2 139
Input18
Output30 41 5 10 25
2 seconds
256 megabytes
['constructive algorithms', '*1400']
F. Cities Excursionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y.A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once.A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi ≠ qi.There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj. For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons: there is no path from sj to tj; there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi ≠ qi. The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj).For each triple sj, tj, kj (1 ≀ j ≀ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any.InputThe first line contains three integers n, m and q (2 ≀ n ≀ 3000,0 ≀ m ≀ 3000, 1 ≀ q ≀ 4Β·105) β€” the number of cities, the number of roads and the number of excursions.Each of the next m lines contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi ≠ yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities.Each of the next q lines contains three integers sj, tj and kj (1 ≀ sj, tj ≀ n, sj ≠ tj, 1 ≀ kj ≀ 3000).OutputIn the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line.ExampleInput7 7 51 22 31 33 44 55 34 61 4 22 6 11 7 31 3 21 3 5Output2-1-12-1
Input7 7 51 22 31 33 44 55 34 61 4 22 6 11 7 31 3 21 3 5
Output2-1-12-1
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*2700']
E. Firetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved.Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started.InputThe first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house.Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i.OutputIn the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.ExamplesInput33 7 42 6 53 7 6Output1122 3 Input25 6 13 3 5Output111 NoteIn the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Input33 7 42 6 53 7 6
Output1122 3
2 seconds
256 megabytes
['dp', 'sortings', '*2000']
D. Make a Permutation!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan has an array consisting of n elements. Each of the elements is an integer from 1 to n.Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal β€” compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if xi < yi, where i is the first index in which the permutations x and y differ.Determine the array Ivan will obtain after performing all the changes.InputThe first line contains an single integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Ivan's array.The second line contains a sequence of integers a1, a2, ..., an (1 ≀ ai ≀ n) β€” the description of Ivan's array.OutputIn the first line print q β€” the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.ExamplesInput43 2 2 3Output21 2 4 3 Input64 5 6 3 2 1Output04 5 6 3 2 1 Input106 8 4 6 7 1 6 3 4 5Output32 8 4 6 7 1 9 3 10 5 NoteIn the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers β€” this permutation is lexicographically minimal among all suitable. In the second example Ivan does not need to change anything because his array already is a permutation.
Input43 2 2 3
Output21 2 4 3
2 seconds
256 megabytes
['greedy', 'implementation', 'math', '*1500']
C. Bustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from x = 0 to x = a and back. Moving from the point x = 0 to x = a or from the point x = a to x = 0 is called a bus journey. In total, the bus must make k journeys.The petrol tank of the bus can hold b liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.There is a gas station in point x = f. This point is between points x = 0 and x = a. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain b liters of gasoline.What is the minimum number of times the bus needs to refuel at the point x = f to make k journeys? The first journey starts in the point x = 0.InputThe first line contains four integers a, b, f, k (0 < f < a ≀ 106, 1 ≀ b ≀ 109, 1 ≀ k ≀ 104) β€” the endpoint of the first bus journey, the capacity of the fuel tank of the bus, the point where the gas station is located, and the required number of journeys.OutputPrint the minimum number of times the bus needs to refuel to make k journeys. If it is impossible for the bus to make k journeys, print -1.ExamplesInput6 9 2 4Output4Input6 10 2 4Output2Input6 5 4 3Output-1NoteIn the first example the bus needs to refuel during each journey.In the second example the bus can pass 10 units of distance without refueling. So the bus makes the whole first journey, passes 4 units of the distance of the second journey and arrives at the point with the gas station. Then it can refuel its tank, finish the second journey and pass 2 units of distance from the third journey. In this case, it will again arrive at the point with the gas station. Further, he can refill the tank up to 10 liters to finish the third journey and ride all the way of the fourth journey. At the end of the journey the tank will be empty. In the third example the bus can not make all 3 journeys because if it refuels during the second journey, the tanks will contain only 5 liters of gasoline, but the bus needs to pass 8 units of distance until next refueling.
Input6 9 2 4
Output4
2 seconds
256 megabytes
['greedy', 'implementation', 'math', '*1500']
B. Polycarp and Letterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.Let A be a set of positions in the string. Let's call it pretty if following conditions are met: letters on positions from A in the string are all distinct and lowercase; there are no uppercase letters in the string which are situated between positions from A (i.e. there is no such j that s[j] is an uppercase letter, and a1 < j < a2 for some a1 and a2 from A). Write a program that will determine the maximum number of elements in a pretty set of positions.InputThe first line contains a single integer n (1 ≀ n ≀ 200) β€” length of string s.The second line contains a string s consisting of lowercase and uppercase Latin letters.OutputPrint maximum number of elements in pretty set of positions for string s.ExamplesInput11aaaaBaabAbAOutput2Input12zACaAbbaazzCOutput3Input3ABCOutput0NoteIn the first example the desired positions might be 6 and 8 or 7 and 8. Positions 6 and 7 contain letters 'a', position 8 contains letter 'b'. The pair of positions 1 and 8 is not suitable because there is an uppercase letter 'B' between these position.In the second example desired positions can be 7, 8 and 11. There are other ways to choose pretty set consisting of three elements.In the third example the given string s does not contain any lowercase letters, so the answer is 0.
Input11aaaaBaabAbA
Output2
2 seconds
256 megabytes
['brute force', 'implementation', 'strings', '*1000']
A. Fair Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card.Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with number he chose. For example, if Petya chose number 5 before the game he will take all cards on which 5 is written and if Vasya chose number 10 before the game he will take all cards on which 10 is written.The game is considered fair if Petya and Vasya can take all n cards, and the number of cards each player gets is the same.Determine whether Petya and Vasya can choose integer numbers before the game so that the game is fair. InputThe first line contains a single integer n (2 ≀ n ≀ 100) β€” number of cards. It is guaranteed that n is an even number.The following n lines contain a sequence of integers a1, a2, ..., an (one integer per line, 1 ≀ ai ≀ 100) β€” numbers written on the n cards.OutputIf it is impossible for Petya and Vasya to choose numbers in such a way that the game will be fair, print "NO" (without quotes) in the first line. In this case you should not print anything more.In the other case print "YES" (without quotes) in the first line. In the second line print two distinct integers β€” number that Petya should choose and the number that Vasya should choose to make the game fair. If there are several solutions, print any of them.ExamplesInput411272711OutputYES11 27Input266OutputNOInput6102030201020OutputNOInput6112233OutputNONoteIn the first example the game will be fair if, for example, Petya chooses number 11, and Vasya chooses number 27. Then the will take all cards β€” Petya will take cards 1 and 4, and Vasya will take cards 2 and 3. Thus, each of them will take exactly two cards.In the second example fair game is impossible because the numbers written on the cards are equal, but the numbers that Petya and Vasya should choose should be distinct.In the third example it is impossible to take all cards. Petya and Vasya can take at most five cards β€” for example, Petya can choose number 10 and Vasya can choose number 20. But for the game to be fair it is necessary to take 6 cards.
Input411272711
OutputYES11 27
1 second
256 megabytes
['implementation', 'sortings', '*1000']
G. Graphic Settingstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Ivan bought a new computer. Excited, he unpacked it and installed his favourite game. With his old computer Ivan had to choose the worst possible graphic settings (because otherwise the framerate would be really low), but now he wants to check, maybe his new computer can perform well even with the best possible graphics?There are m graphics parameters in the game. i-th parameter can be set to any positive integer from 1 to ai, and initially is set to bi (bi ≀ ai). So there are different combinations of parameters. Ivan can increase or decrease any of these parameters by 1; after that the game will be restarted with new parameters (and Ivan will have the opportunity to check chosen combination of parameters).Ivan wants to try all p possible combinations. Also he wants to return to the initial settings after trying all combinations, because he thinks that initial settings can be somehow best suited for his hardware. But Ivan doesn't really want to make a lot of restarts.So he wants you to tell the following: If there exists a way to make exactly p changes (each change either decreases or increases some parameter by 1) to try all possible combinations and return to initial combination, then Ivan wants to know this way. Otherwise, if there exists a way to make exactly p - 1 changes to try all possible combinations (including the initial one), then Ivan wants to know this way. Help Ivan by showing him the way to change parameters!InputThe first line of input contains one integer number m (1 ≀ m ≀ 6).The second line contains m integer numbers a1, a2, ..., am (2 ≀ ai ≀ 1000). It is guaranteed that .The third line contains m integer numbers b1, b2, ..., bm (1 ≀ bi ≀ ai).OutputIf there is a way to make exactly p changes (each change either decreases or increases some parameter by 1) to try all possible combinations and return to initial combination, then output Cycle in the first line. Then p lines must follow, each desribing a change. The line must be either inc x (increase parameter x by 1) or dec x (decrease it).Otherwise, if there is a way to make exactly p - 1 changes to try all possible combinations (including the initial one), then output Path in the first line. Then p - 1 lines must follow, each describing the change the same way as mentioned above.Otherwise, output No.ExamplesInput131OutputPathinc 1inc 1Input132OutputNoInput23 21 1OutputCycleinc 1inc 1inc 2dec 1dec 1dec 2
Input131
OutputPathinc 1inc 1
2 seconds
256 megabytes
['*3200']
F. Almost Permutationtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows:, where cnt(i) is the number of occurences of i in the array.Help Ivan to determine minimum possible cost of the array that corresponds to the facts!InputThe first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100).Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact).OutputIf the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array.ExamplesInput3 0Output3Input3 11 1 3 2Output5Input3 21 1 3 22 1 3 2Output9Input3 21 1 3 22 1 3 1Output-1
Input3 0
Output3
3 seconds
512 megabytes
['flows', '*2200']
E. Turn Off The TVtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuba needs your help again! Luba has n TV sets. She knows that i-th TV set will be working from moment of time li till moment ri, inclusive.Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of integer moments of time when at least one of TV sets is working won't decrease. Luba will be very upset if she has to switch off a non-redundant TV set.Help Luba by telling her the index of some redundant TV set. If there is no any, print -1.InputThe first line contains one integer number nΒ (1 ≀ n ≀ 2Β·105) β€” the number of TV sets.Then n lines follow, each of them containing two integer numbers li, riΒ (0 ≀ li ≀ ri ≀ 109) denoting the working time of i-th TV set.OutputIf there is no any redundant TV set, print -1. Otherwise print the index of any redundant TV set (TV sets are indexed from 1 to n).If there are multiple answers, print any of them.ExamplesInput31 34 61 7Output1Input20 100 10Output1Input31 23 46 8Output-1Input31 22 33 4Output2NoteConsider the first sample. Initially all integer moments of time such that at least one TV set is working are from the segment [1;7]. It's easy to see that this segment won't change if we switch off the first TV set (or the second one).Note that in the fourth sample you can switch off the second TV set, since even without it all integer moments such that any of the TV sets is working denote the segment [1;4].
Input31 34 61 7
Output1
2 seconds
256 megabytes
['data structures', 'sortings', '*2000']
D. Yet Another Array Queries Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of size n, and q queries to it. There are queries of two types: 1 li ri β€” perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li ≀ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari; 2 li ri β€” reverse the segment [li, ri]. There are m important indices in the array b1, b2, ..., bm. For each i such that 1 ≀ i ≀ m you have to output the number that will have index bi in the array after all queries are performed.InputThe first line contains three integer numbers n, q and m (1 ≀ n, q ≀ 2Β·105, 1 ≀ m ≀ 100). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109). Then q lines follow. i-th of them contains three integer numbers ti, li, ri, where ti is the type of i-th query, and [li, ri] is the segment where this query is performed (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). The last line contains m integer numbers b1, b2, ..., bm (1 ≀ bi ≀ n) β€” important indices of the array. OutputPrint m numbers, i-th of which is equal to the number at index bi after all queries are done.ExampleInput6 3 51 2 3 4 5 62 1 32 3 61 1 62 2 1 5 3Output3 3 1 5 2
Input6 3 51 2 3 4 5 62 1 32 3 61 1 62 2 1 5 3
Output3 3 1 5 2
2 seconds
256 megabytes
['data structures', 'implementation', '*1800']
C. 1-2-3time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice". So now Ilya wants to compare his robots' performance in a simple game called "1-2-3". This game is similar to the "Rock-Paper-Scissors" game: both robots secretly choose a number from the set {1, 2, 3} and say it at the same moment. If both robots choose the same number, then it's a draw and noone gets any points. But if chosen numbers are different, then one of the robots gets a point: 3 beats 2, 2 beats 1 and 1 beats 3. Both robots' programs make them choose their numbers in such a way that their choice in (i + 1)-th game depends only on the numbers chosen by them in i-th game. Ilya knows that the robots will play k games, Alice will choose number a in the first game, and Bob will choose b in the first game. He also knows both robots' programs and can tell what each robot will choose depending on their choices in previous game. Ilya doesn't want to wait until robots play all k games, so he asks you to predict the number of points they will have after the final game. InputThe first line contains three numbers k, a, b (1 ≀ k ≀ 1018, 1 ≀ a, b ≀ 3). Then 3 lines follow, i-th of them containing 3 numbers Ai, 1, Ai, 2, Ai, 3, where Ai, j represents Alice's choice in the game if Alice chose i in previous game and Bob chose j (1 ≀ Ai, j ≀ 3). Then 3 lines follow, i-th of them containing 3 numbers Bi, 1, Bi, 2, Bi, 3, where Bi, j represents Bob's choice in the game if Alice chose i in previous game and Bob chose j (1 ≀ Bi, j ≀ 3). OutputPrint two numbers. First of them has to be equal to the number of points Alice will have, and second of them must be Bob's score after k games.ExamplesInput10 2 11 1 11 1 11 1 12 2 22 2 22 2 2Output1 9Input8 1 12 2 13 3 13 1 31 1 12 1 11 2 3Output5 2Input5 1 11 2 22 2 22 2 21 2 22 2 22 2 2Output0 0NoteIn the second example game goes like this:The fourth and the seventh game are won by Bob, the first game is draw and the rest are won by Alice.
Input10 2 11 1 11 1 11 1 12 2 22 2 22 2 2
Output1 9
1 second
256 megabytes
['graphs', 'implementation', '*1800']
B. Kayakingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is wi, and weight is an important matter in kayaking β€” if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.Help the party to determine minimum possible total instability! InputThe first line contains one number n (2 ≀ n ≀ 50).The second line contains 2Β·n integer numbers w1, w2, ..., w2n, where wi is weight of person i (1 ≀ wi ≀ 1000).OutputPrint minimum possible total instability.ExamplesInput21 2 3 4Output1Input41 3 4 6 3 4 100 200Output5
Input21 2 3 4
Output1
2 seconds
256 megabytes
['brute force', 'greedy', 'sortings', '*1500']
A. Quasi-palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left.For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.You are given some integer number x. Check if it's a quasi-palindromic number.InputThe first line contains one integer number x (1 ≀ x ≀ 109). This number is given without any leading zeroes.OutputPrint "YES" if number x is quasi-palindromic. Otherwise, print "NO" (without quotes).ExamplesInput131OutputYESInput320OutputNOInput2010200OutputYES
Input131
OutputYES
1 second
256 megabytes
['brute force', 'implementation', '*900']
F. Mahmoud and Ehab and the final stagetime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMahmoud and Ehab solved Dr. Evil's questions so he gave them the password of the door of the evil land. When they tried to open the door using it, the door gave them a final question to solve before they leave (yes, the door is digital, Dr. Evil is modern). If they don't solve it, all the work will be useless and they won't leave the evil land forever. Will you help them?Mahmoud and Ehab are given n strings s1, s2, ... , sn numbered from 1 to n and q queries, Each query has one of the following forms: 1 a b (1 ≀ a ≀ b ≀ n), For all the intervals [l;r] where (a ≀ l ≀ r ≀ b) find the maximum value of this expression:(r - l + 1) * LCP(sl, sl + 1, ... , sr - 1, sr) where LCP(str1, str2, str3, ... ) is the length of the longest common prefix of the strings str1, str2, str3, ... . 2 x y (1 ≀ x ≀ n) where y is a string, consisting of lowercase English letters. Change the string at position x to y.InputThe first line of input contains 2 integers n and q (1 ≀ n ≀ 105, 1 ≀ q ≀ 105) – The number of strings and the number of queries, respectively.The second line contains n strings stri consisting of lowercase English letters.The next q lines describe the queries and may have one of the 2 forms: 1 a b (1 ≀ a ≀ b ≀ n). 2 x y (1 ≀ x ≀ n), where y is a string consisting of lowercase English letters.the total length of all strings in input won't exceed 105OutputFor each query of first type output its answer in a new line.ExampleInput5 9mahmoud mahmoudbadawy drmahmoud drevil mahmoud1 1 51 1 21 2 32 3 mahmoud2 4 mahmoud2 2 mahmouu1 1 51 2 31 1 1Output14141330127
Input5 9mahmoud mahmoudbadawy drmahmoud drevil mahmoud1 1 51 1 21 2 32 3 mahmoud2 4 mahmoud2 2 mahmouu1 1 51 2 31 1 1
Output14141330127
5 seconds
512 megabytes
['data structures', 'strings', '*2900']
E. Mahmoud and Ehab and the functiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≀ j ≀ m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, . Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer xi to all elements in a in range [li;ri] i.e. they should add xi to ali, ali + 1, ... , ari and then they should calculate the minimum value of f(j) for all valid j.Please help Mahmoud and Ehab.InputThe first line contains three integers n, m and q (1 ≀ n ≀ m ≀ 105, 1 ≀ q ≀ 105)Β β€” number of elements in a, number of elements in b and number of queries, respectively.The second line contains n integers a1, a2, ..., an. ( - 109 ≀ ai ≀ 109)Β β€” elements of a.The third line contains m integers b1, b2, ..., bm. ( - 109 ≀ bi ≀ 109)Β β€” elements of b.Then q lines follow describing the queries. Each of them contains three integers li ri xi (1 ≀ li ≀ ri ≀ n,  - 109 ≀ x ≀ 109)Β β€” range to be updated and added value.OutputThe first line should contain the minimum value of the function f before any update.Then output q lines, the i-th of them should contain the minimum value of the function f after performing the i-th update .ExampleInput5 6 31 2 3 4 51 2 3 4 5 61 1 101 1 -91 5 -1Output0900NoteFor the first example before any updates it's optimal to choose j = 0, f(0) = |(1 - 1) - (2 - 2) + (3 - 3) - (4 - 4) + (5 - 5)| = |0| = 0.After the first update a becomes {11, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(11 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6) = |9| = 9.After the second update a becomes {2, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(2 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6)| = |0| = 0.After the third update a becomes {1, 1, 2, 3, 4} and it's optimal to choose j = 0, f(0) = |(1 - 1) - (1 - 2) + (2 - 3) - (3 - 4) + (4 - 5)| = |0| = 0.
Input5 6 31 2 3 4 51 2 3 4 5 61 1 101 1 -91 5 -1
Output0900
2 seconds
256 megabytes
['binary search', 'data structures', 'sortings', '*2100']
D. Mahmoud and Ehab and the binary stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud and Ehab are in the fourth stage now.Dr. Evil has a hidden binary string of length n. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to 15 questions. They tell Dr. Evil some binary string of length n, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.Help Mahmoud and Ehab find these two positions.You will get Wrong Answer verdict if Your queries doesn't satisfy interaction protocol described below. You ask strictly more than 15 questions and your program terminated after exceeding queries limit. Please note, that you can do up to 15 ask queries and one answer query. Your final answer is not correct. You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .InputThe first line of input will contain a single integer n (2 ≀ n ≀ 1000)Β β€” the length of the hidden binary string.OutputTo print the final answer, print "! pos0 pos1" (without quotes), where pos0 and pos1 are positions of some '0' and some '1' in the string (the string is 1-indexed). Don't forget to flush the output after printing the answer!InteractionTo ask a question use the format "? s" (without quotes), where s is a query string. Don't forget to flush the output after printing a query!After each query you can read a single integer from standard inputΒ β€” the Hamming distance between the hidden string and the query string.To flush the output you can use:- fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages . Hacking. To hack someone just print one binary string with length up to 1000, containing at least one '0' and at least one '1'.ExampleInput3213210Output? 000? 001? 010? 011? 100? 101! 2 1NoteHamming distance definition: https://en.wikipedia.org/wiki/Hamming_distanceIn the first test case the hidden binary string is 101, The first query is 000, so the Hamming distance is 2. In the second query the hidden string is still 101 and query is 001, so the Hamming distance is 1.After some queries you find that symbol at position 2 is '0' and symbol at position 1 is '1', so you print "! 2 1".
Input3213210
Output? 000? 001? 010? 011? 100? 101! 2 1
2 seconds
256 megabytes
['binary search', 'divide and conquer', 'interactive', '*2000']
C. Mahmoud and Ehab and the xortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.InputThe only line contains two integers n and x (1 ≀ n ≀ 105, 0 ≀ x ≀ 105)Β β€” the number of elements in the set and the desired bitwise-xor, respectively.OutputIf there is no such set, print "NO" (without quotes).Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.ExamplesInput5 5OutputYES1 2 4 5 7Input3 6OutputYES1 2 5NoteYou can read more about the bitwise-xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XORFor the first sample .For the second sample .
Input5 5
OutputYES1 2 4 5 7
2 seconds
256 megabytes
['constructive algorithms', '*1900']
B. Mahmoud and Ehab and the bipartitenesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud 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 .InputThe 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. OutputOutput one integerΒ β€” the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.ExamplesInput31 21 3Output0Input51 22 33 44 5Output2NoteTree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)Bipartite graph definition: https://en.wikipedia.org/wiki/Bipartite_graphIn 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).
Input31 21 3
Output0
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*1300']
A. Mahmoud and Ehab and the MEXtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?InputThe first line contains two integers n and x (1 ≀ n ≀ 100, 0 ≀ x ≀ 100)Β β€” the size of the set Dr. Evil owns, and the desired MEX.The second line contains n distinct non-negative integers not exceeding 100 that represent the set.OutputThe only line should contain one integerΒ β€” the minimal number of operations Dr. Evil should perform.ExamplesInput5 30 4 5 6 7Output2Input1 00Output1Input5 01 2 3 4 5Output0NoteFor the first test case Dr. Evil should add 1 and 2 to the set performing 2 operations.For the second test case Dr. Evil should erase 0 from the set. After that, the set becomes empty, so the MEX of it is 0.In the third test case the set is already evil.
Input5 30 4 5 6 7
Output2
2 seconds
256 megabytes
['greedy', 'implementation', '*1000']
E. Arkady and a Nobody-mentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady words in a large company. There are n employees working in a system of a strict hierarchy. Namely, each employee, with an exception of the CEO, has exactly one immediate manager. The CEO is a manager (through a chain of immediate managers) of all employees.Each employee has an integer rank. The CEO has rank equal to 1, each other employee has rank equal to the rank of his immediate manager plus 1.Arkady has a good post in the company, however, he feels that he is nobody in the company's structure, and there are a lot of people who can replace him. He introduced the value of replaceability. Consider an employee a and an employee b, the latter being manager of a (not necessarily immediate). Then the replaceability r(a, b) of a with respect to b is the number of subordinates (not necessarily immediate) of the manager b, whose rank is not greater than the rank of a. Apart from replaceability, Arkady introduced the value of negligibility. The negligibility za of employee a equals the sum of his replaceabilities with respect to all his managers, i.e. , where the sum is taken over all his managers b.Arkady is interested not only in negligibility of himself, but also in negligibility of all employees in the company. Find the negligibility of each employee for Arkady.InputThe first line contains single integer n (1 ≀ n ≀ 5Β·105)Β β€” the number of employees in the company.The second line contains n integers p1, p2, ..., pn (0 ≀ pi ≀ n), where pi = 0 if the i-th employee is the CEO, otherwise pi equals the id of the immediate manager of the employee with id i. The employees are numbered from 1 to n. It is guaranteed that there is exactly one 0 among these values, and also that the CEO is a manager (not necessarily immediate) for all the other employees.OutputPrint n integersΒ β€” the negligibilities of all employees in the order of their ids: z1, z2, ..., zn.ExamplesInput40 1 2 1Output0 2 4 2 Input52 3 4 5 0Output10 6 3 1 0 Input50 1 1 1 3Output0 3 3 3 5 NoteConsider the first example: The CEO has no managers, thus z1 = 0. r(2, 1) = 2 (employees 2 and 4 suit the conditions, employee 3 has too large rank). Thus z2 = r(2, 1) = 2. Similarly, z4 = r(4, 1) = 2. r(3, 2) = 1 (employee 3 is a subordinate of 2 and has suitable rank). r(3, 1) = 3 (employees 2, 3, 4 suit the conditions). Thus z3 = r(3, 2) + r(3, 1) = 4.
Input40 1 2 1
Output0 2 4 2
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'trees', '*2700']
G. Circle of Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number k. Then you may repeatedly select a set of 2 or more points which are evenly spaced, and either increase all numbers at points in the set by k or decrease all numbers at points in the set by k. You would like to eventually end up with all numbers equal to 0. Is it possible?A set of 2 points is considered evenly spaced if they are diametrically opposed, and a set of 3 or more points is considered evenly spaced if they form a regular polygon.InputThe first line of input contains an integer n (3 ≀ n ≀ 100000), the number of points along the circle.The following line contains a string s with exactly n digits, indicating the numbers initially present at each of the points, in clockwise order.OutputPrint "YES" (without quotes) if there is some sequence of operations that results in all numbers being 0, otherwise "NO" (without quotes).You can print each letter in any case (upper or lower).ExamplesInput30000100000100000110000000001100OutputYESInput6314159OutputNONoteIf we label the points from 1 to n, then for the first test case we can set k = 1. Then we increase the numbers at points 7 and 22 by 1, then decrease the numbers at points 7, 17, and 27 by 1, then decrease the numbers at points 4, 10, 16, 22, and 28 by 1.
Input30000100000100000110000000001100
OutputYES
1 second
256 megabytes
['math', '*3000']
F. Ordering T-Shirtstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's another Start[c]up, and that means there are T-shirts to order. In order to make sure T-shirts are shipped as soon as possible, we've decided that this year we're going to order all of the necessary T-shirts before the actual competition. The top C contestants are going to be awarded T-shirts, but we obviously don't know which contestants that will be. The plan is to get the T-Shirt sizes of all contestants before the actual competition, and then order enough T-shirts so that no matter who is in the top C we'll have T-shirts available in order to award them.In order to get the T-shirt sizes of the contestants, we will send out a survey. The survey will allow contestants to either specify a single desired T-shirt size, or two adjacent T-shirt sizes. If a contestant specifies two sizes, it means that they can be awarded either size.As you can probably tell, this plan could require ordering a lot of unnecessary T-shirts. We'd like your help to determine the minimum number of T-shirts we'll need to order to ensure that we'll be able to award T-shirts no matter the outcome of the competition.InputInput will begin with two integers N and C (1 ≀ N ≀ 2Β·105, 1 ≀ C), the number of T-shirt sizes and number of T-shirts to be awarded, respectively.Following this is a line with 2Β·N - 1 integers, s1 through s2Β·N - 1 (0 ≀ si ≀ 108). For odd i, si indicates the number of contestants desiring T-shirt size ((i + 1) / 2). For even i, si indicates the number of contestants okay receiving either of T-shirt sizes (i / 2) and (i / 2 + 1). C will not exceed the total number of contestants.OutputPrint the minimum number of T-shirts we need to buy.ExamplesInput2 200100 250 100Output200Input4 16088 69 62 29 58 52 44Output314NoteIn the first example, we can buy 100 of each size.
Input2 200100 250 100
Output200
2 seconds
256 megabytes
['greedy', '*2800']
E. Desk Disordertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.InputInput will begin with a line containing N (1 ≀ N ≀ 100000), the number of engineers. N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2Β·N. It is guaranteed that no two engineers sit at the same desk.OutputPrint the number of possible assignments, modulo 1000000007 = 109 + 7.ExamplesInput41 55 23 77 3Output6Input51 102 103 104 105 5Output5NoteThese are the possible assignments for the first example: 1 5 3 7 1 2 3 7 5 2 3 7 1 5 7 3 1 2 7 3 5 2 7 3
Input41 55 23 77 3
Output6
2 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'dsu', 'graphs', 'trees', '*2100']
D. Third Month Insanitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2Β·i - 1 will play against team 2Β·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2Β·i - 1 will play against the winner of the previous round's game 2Β·i.Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.InputInput will begin with a line containing N (2 ≀ N ≀ 6).2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.OutputPrint the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if .ExamplesInput20 40 100 10060 0 40 400 60 0 450 60 55 0Output1.75Input30 0 100 0 100 0 0 0100 0 100 0 0 0 100 1000 0 0 100 100 0 0 0100 100 0 0 0 0 100 1000 100 0 100 0 0 100 0100 100 100 100 100 0 0 0100 0 100 0 0 100 0 0100 0 100 0 100 100 100 0Output12Input20 21 41 2679 0 97 3359 3 0 9174 67 9 0Output3.141592NoteIn the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
Input20 40 100 10060 0 40 400 60 0 450 60 55 0
Output1.75
2 seconds
256 megabytes
['dp', 'probabilities', 'trees', '*2100']
C. Pie Rulestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.The way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the "decider" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left.All of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?InputInput will begin with an integer N (1 ≀ N ≀ 50), the number of slices of pie. Following this is a line with N integers indicating the sizes of the slices (each between 1 and 100000, inclusive), in the order in which they must be handed out.OutputPrint two integers. First, the sum of the sizes of slices eaten by Alice, then the sum of the sizes of the slices eaten by Bob, assuming both players make their decisions optimally.ExamplesInput3141 592 653Output653 733Input510 21 10 21 10Output31 41NoteIn the first example, Bob takes the size 141 slice for himself and gives the decider token to Alice. Then Alice gives the size 592 slice to Bob and keeps the decider token for herself, so that she can then give the size 653 slice to herself.
Input3141 592 653
Output653 733
2 seconds
256 megabytes
['dp', 'games', '*1500']
B. Lazy Security Guardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.InputInput will consist of a single integer N (1 ≀ N ≀ 106), the number of city blocks that must be enclosed by the route.OutputPrint the minimum perimeter that can be achieved.ExamplesInput4Output8Input11Output14Input22Output20NoteHere are some possible shapes for the examples:
Input4
Output8
2 seconds
256 megabytes
['brute force', 'geometry', 'math', '*1000']
A. Declined Finaliststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible contestant must either accept or decline the invitation. Whenever a contestant declines, the highest ranked contestant not yet invited is invited to take the place of the one that declined. This continues until 25 contestants have accepted invitations.After the qualifying round completes, you know K of the onsite finalists, as well as their qualifying ranks (which start at 1, there are no ties). Determine the minimum possible number of contestants that declined the invitation to compete onsite in the final round.InputThe first line of input contains K (1 ≀ K ≀ 25), the number of onsite finalists you know. The second line of input contains r1, r2, ..., rK (1 ≀ ri ≀ 106), the qualifying ranks of the finalists you know. All these ranks are distinct.OutputPrint the minimum possible number of contestants that declined the invitation to compete onsite.ExamplesInput252 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 28Output3Input516 23 8 15 4Output0Input314 15 92Output67NoteIn the first example, you know all 25 onsite finalists. The contestants who ranked 1-st, 13-th, and 27-th must have declined, so the answer is 3.
Input252 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 28
Output3
2 seconds
256 megabytes
['greedy', 'implementation', '*800']
F. Wizard's Tourtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAll Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland!It is well-known that there are n cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other.The tour will contain several episodes. In each of the episodes: the wizard will disembark at some city x from the Helicopter; he will give a performance and show a movie for free at the city x; he will drive to some neighboring city y using a road; he will give a performance and show a movie for free at the city y; he will drive to some neighboring to y city z; he will give a performance and show a movie for free at the city z; he will embark the Helicopter and fly away from the city z. It is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between a and b he only can drive once from a to b, or drive once from b to a, or do not use this road at all.The wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard!Please note that the wizard can visit the same city multiple times, the restriction is on roads only.InputThe first line contains two integers n, m (1 ≀ n ≀ 2Β·105, 0 ≀ m ≀ 2Β·105) β€” the number of cities and the number of roads in Berland, respectively.The roads description follow, one in each line. Each description is a pair of two integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi), where ai and bi are the ids of the cities connected by the i-th road. It is guaranteed that there are no two roads connecting the same pair of cities. Every road is bidirectional. The cities are numbered from 1 to n.It is possible that the road network in Berland is not connected.OutputIn the first line print w β€” the maximum possible number of episodes. The next w lines should contain the episodes in format x, y, z β€” the three integers denoting the ids of the cities in the order of the wizard's visits.ExamplesInput4 51 23 22 43 44 1Output21 4 24 3 2Input5 85 31 24 55 12 54 31 43 2Output41 4 52 3 41 5 35 2 1
Input4 51 23 22 43 44 1
Output21 4 24 3 2
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*2300']
E. Tests Renumerationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "n', where n is the total number of tests.Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command.Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run: all examples are the first several tests having filenames "1", "2", ..., "e", where e is the total number of examples; all other files contain regular tests with filenames "e + 1", "e + 2", ..., "n", where n is the total number of all tests. InputThe first line contains single integer n (1 ≀ n ≀ 105) β€” the number of files with tests.n lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the i-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct.OutputIn the first line print the minimum number of lines in Vladimir's script file.After that print the script file, each line should be "move file_1 file_2", where "file_1" is an existing at the moment of this line being run filename, and "file_2" β€” is a string of digits and small English letters with length from 1 to 6.ExamplesInput501 02 12extra 03 199 0Output4move 3 1move 01 5move 2extra 4move 99 3Input21 02 1Output3move 1 3move 2 1move 3 2Input51 011 1111 01111 111111 0Output5move 1 5move 11 1move 1111 2move 111 4move 11111 3
Input501 02 12extra 03 199 0
Output4move 3 1move 01 5move 2extra 4move 99 3
2 seconds
256 megabytes
['greedy', 'implementation', '*2200']