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
E. Cross Sumtime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGenos has been given n distinct lines on the Cartesian plane. Let be a list of intersection points of these lines. A single point might appear multiple times in this list if it is the intersection of multiple pairs of lines. The order of the list does not matter.Given a query point (p, q), let be the corresponding list of distances of all points in to the query point. Distance here refers to euclidean distance. As a refresher, the euclidean distance between two points (x1, y1) and (x2, y2) is .Genos is given a point (p, q) and a positive integer m. He is asked to find the sum of the m smallest elements in . Duplicate elements in are treated as separate elements. Genos is intimidated by Div1 E problems so he asked for your help.InputThe first line of the input contains a single integer n (2 ≀ n ≀ 50 000)Β β€” the number of lines.The second line contains three integers x, y and m (|x|, |y| ≀ 1 000 000, )Β β€” the encoded coordinates of the query point and the integer m from the statement above. The query point (p, q) is obtained as . In other words, divide x and y by 1000 to get the actual query point. denotes the length of the list and it is guaranteed that .Each of the next n lines contains two integers ai and bi (|ai|, |bi| ≀ 1 000 000)Β β€” the parameters for a line of the form: . It is guaranteed that no two lines are the same, that is (ai, bi) ≠ (aj, bj) if i ≠ j.OutputPrint a single real number, the sum of m smallest elements of . Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.To clarify, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput41000 1000 31000 0-1000 00 50000 -5000Output14.282170363Input2-1000000 -1000000 11000000 -1000000999999 1000000Output2000001000.999999500Input3-1000 1000 31000 0-1000 20002000 -1000Output6.000000000Input5-303667 189976 10-638 116487-581 443371231 -7568441427 -440978271 -838417Output12953.274911829NoteIn the first sample, the three closest points have distances and .In the second sample, the two lines y = 1000x - 1000 and intersect at (2000000, 1999999000). This point has a distance of from ( - 1000,  - 1000).In the third sample, the three lines all intersect at the point (1, 1). This intersection point is present three times in since it is the intersection of three pairs of lines. Since the distance between the intersection point and the query point is 2, the answer is three times that or 6.
Input41000 1000 31000 0-1000 00 50000 -5000
Output14.282170363
7 seconds
512 megabytes
['binary search', 'geometry', '*3300']
D. Power Treetime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGenos and Saitama went shopping for Christmas trees. However, a different type of tree caught their attention, the exalted Power Tree. A Power Tree starts out as a single root vertex indexed 1. A Power Tree grows through a magical phenomenon known as an update. In an update, a single vertex is added to the tree as a child of some other vertex.Every vertex in the tree (the root and all the added vertices) has some value vi associated with it. The power of a vertex is defined as the strength of the multiset composed of the value associated with this vertex (vi) and the powers of its direct children. The strength of a multiset is defined as the sum of all elements in the multiset multiplied by the number of elements in it. Or in other words for some multiset S: Saitama knows the updates that will be performed on the tree, so he decided to test Genos by asking him queries about the tree during its growth cycle.An update is of the form 1Β pΒ v, and adds a new vertex with value v as a child of vertex p.A query is of the form 2Β u, and asks for the power of vertex u.Please help Genos respond to these queries modulo 109 + 7.InputThe first line of the input contains two space separated integers v1 and q (1 ≀ v1 < 109, 1 ≀ q ≀ 200 000) β€” the value of vertex 1 and the total number of updates and queries respectively.The next q lines contain the updates and queries. Each of them has one of the following forms: 1Β piΒ vi, if these line describes an update. The index of the added vertex is equal to the smallest positive integer not yet used as an index in the tree. It is guaranteed that pi is some already existing vertex and 1 ≀ vi < 109. 2Β ui, if these line describes a query. It is guaranteed ui will exist in the tree. It is guaranteed that the input will contain at least one query.OutputFor each query, print out the power of the given vertex modulo 109 + 7.ExamplesInput2 51 1 31 2 51 3 71 4 112 1Output344Input5 51 1 41 2 32 21 2 72 1Output1494NoteFor the first sample case, after all the updates the graph will have vertices labelled in the following manner: 1 β€” 2 β€” 3 β€” 4 β€” 5These vertices will have corresponding values: 2 β€” 3 β€” 5 β€” 7 β€” 11And corresponding powers: 344 β€” 170 β€” 82 β€” 36 β€” 11
Input2 51 1 31 2 51 3 71 4 112 1
Output344
3.5 seconds
256 megabytes
['data structures', 'trees', '*2600']
C. Marblestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.InputThe first line of the input contains a single integer n (2 ≀ n ≀ 1 000 000)Β β€” the length of the paths.The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W')Β β€” the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W')Β β€” the second grid path.OutputPrint "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.ExamplesInput7NNESWWSWSWSWOutputYESInput3NNSSOutputNONoteIn the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.In the second sample, no sequence of moves can get both marbles to the end.
Input7NNESWWSWSWSW
OutputYES
2 seconds
256 megabytes
['hashing', 'strings', '*2500']
B. Zumatime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGenos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.InputThe first line of input contains a single integer n (1 ≀ n ≀ 500)Β β€” the number of gemstones.The second line contains n space-separated integers, the i-th of which is ci (1 ≀ ci ≀ n)Β β€” the color of the i-th gemstone in a line.OutputPrint a single integerΒ β€” the minimum number of seconds needed to destroy the entire line.ExamplesInput31 2 1Output1Input31 2 3Output3Input71 4 4 2 3 2 1Output2NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.
Input31 2 1
Output1
2 seconds
512 megabytes
['dp', '*1900']
A. Chain Reactiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.InputThe first line of input contains a single integer n (1 ≀ n ≀ 100 000) β€” the initial number of beacons.The i-th of next n lines contains two integers ai and bi (0 ≀ ai ≀ 1 000 000, 1 ≀ bi ≀ 1 000 000)Β β€” the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j.OutputPrint a single integerΒ β€” the minimum number of beacons that could be destroyed if exactly one beacon is added.ExamplesInput41 93 16 17 4Output1Input71 12 13 14 15 16 17 1Output3NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.
Input41 93 16 17 4
Output1
2 seconds
256 megabytes
['binary search', 'dp', '*1600']
B. Testing Robotstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0, y0) of a rectangular squared field of size x × y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly xΒ·y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it.The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up.InputThe first line of the input contains four integers x, y, x0, y0 (1 ≀ x, y ≀ 500, 1 ≀ x0 ≀ x, 1 ≀ y0 ≀ y)Β β€” the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right.The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100 000 characters and only consists of characters 'L', 'R', 'U', 'D'.OutputPrint the sequence consisting of (length(s) + 1) numbers. On the k-th position, starting with zero, print the number of tests where the robot will run exactly k commands before it blows up.ExamplesInput3 4 2 2UURDRDRLOutput1 1 0 1 1 1 1 0 6Input2 2 2 2ULDOutput1 1 1 1NoteIn the first sample, if we exclude the probable impact of the mines, the robot's route will look like that: .
Input3 4 2 2UURDRDRL
Output1 1 0 1 1 1 1 0 6
2 seconds
256 megabytes
['implementation', '*1600']
A. Magic Spherestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCarl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple actions)?InputThe first line of the input contains three integers a, b and c (0 ≀ a, b, c ≀ 1 000 000)Β β€” the number of blue, violet and orange spheres that are in the magician's disposal.The second line of the input contains three integers, x, y and z (0 ≀ x, y, z ≀ 1 000 000)Β β€” the number of blue, violet and orange spheres that he needs to get.OutputIf the wizard is able to obtain the required numbers of spheres, print "Yes". Otherwise, print "No".ExamplesInput4 4 02 1 2OutputYesInput5 6 12 7 2OutputNoInput3 3 32 2 2OutputYesNoteIn the first sample the wizard has 4 blue and 4 violet spheres. In his first action he can turn two blue spheres into one violet one. After that he will have 2 blue and 5 violet spheres. Then he turns 4 violet spheres into 2 orange spheres and he ends up with 2 blue, 1 violet and 2 orange spheres, which is exactly what he needs.
Input4 4 02 1 2
OutputYes
2 seconds
256 megabytes
['implementation', '*1200']
E. Intergalaxy Tripstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe scientists have recently discovered wormholesΒ β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day.Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 1000)Β β€” the number of galaxies within reach.Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100.OutputPrint a single real valueΒ β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput3100 50 500 100 800 0 100Output1.750000000000000Input2100 3040 100Output3.333333333333333NoteIn the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is .
Input3100 50 500 100 800 0 100
Output1.750000000000000
2 seconds
256 megabytes
['probabilities', 'shortest paths', '*2700']
D. Board Gametime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a board card game. In this game the player has two characteristics, x and yΒ β€” the white magic skill and the black magic skill, respectively. There are n spell cards lying on the table, each of them has four characteristics, ai, bi, ci and di. In one move a player can pick one of the cards and cast the spell written on it, but only if first two of it's characteristics meet the requirement ai ≀ x and bi ≀ y, i.e. if the player has enough magic skill to cast this spell. However, after casting the spell the characteristics of a player change and become equal to x = ci and y = di.At the beginning of the game both characteristics of a player are equal to zero. The goal of the game is to cast the n-th spell. Your task is to make it in as few moves as possible. You are allowed to use spell in any order and any number of times (for example, you may not use some spells at all).InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of cards on the table.Each of the next n lines contains four integers ai, bi, ci, di (0 ≀ ai, bi, ci, di ≀ 109)Β β€” the characteristics of the corresponding card.OutputIn the first line print a single integer kΒ β€” the minimum number of moves needed to cast the n-th spell and in the second line print k numbersΒ β€” the indices of the cards in the order in which you should cast them. In case there are multiple possible solutions, print any of them.If it is impossible to cast the n-th spell, print  - 1.ExamplesInput40 0 3 42 2 5 34 1 1 75 3 8 8Output31 2 4Input20 0 4 65 1 1000000000 1000000000Output-1
Input40 0 3 42 2 5 34 1 1 75 3 8 8
Output31 2 4
2.5 seconds
256 megabytes
['data structures', 'dfs and similar', '*2500']
C. Freelancer's Dreamstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by ai per day and bring bi dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true.For example, suppose Mikhail is suggested to work on three projects and a1 = 6, b1 = 2, a2 = 1, b2 = 3, a3 = 2, b3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a1Β·2.5 + a2Β·0 + a3Β·2.5 = 6Β·2.5 + 1Β·0 + 2Β·2.5 = 20 and b1Β·2.5 + b2Β·0 + b3Β·2.5 = 2Β·2.5 + 3Β·0 + 6Β·2.5 = 20.InputThe first line of the input contains three integers n, p and q (1 ≀ n ≀ 100 000, 1 ≀ p, q ≀ 1 000 000)Β β€” the number of projects and the required number of experience and money.Each of the next n lines contains two integers ai and bi (1 ≀ ai, bi ≀ 1 000 000)Β β€” the daily increase in experience and daily income for working on the i-th project.OutputPrint a real valueΒ β€” the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput3 20 206 21 32 6Output5.000000000000000Input4 1 12 33 22 33 2Output0.400000000000000NoteFirst sample corresponds to the example in the problem statement.
Input3 20 206 21 32 6
Output5.000000000000000
2 seconds
256 megabytes
['geometry', '*2400']
B. Lazy Studenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudent Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graphΒ β€” something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.InputThe first line of the input contains two integers n and m ()Β β€” the number of vertices and the number of edges in the graph.Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≀ aj ≀ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.OutputIf Vladislav has made a mistake and such graph doesn't exist, print  - 1.Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≀ uj, vj ≀ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.ExamplesInput4 52 13 14 01 15 0Output2 41 43 43 13 2Input3 31 02 13 1Output-1
Input4 52 13 14 01 15 0
Output2 41 43 43 13 2
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'graphs', '*1700']
A. Sorting Railway Carstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?InputThe first line of the input contains integer n (1 ≀ n ≀ 100 000)Β β€” the number of cars in the train. The second line contains n integers pi (1 ≀ pi ≀ n, pi ≠ pj if i ≠ j)Β β€” the sequence of the numbers of the cars in the train.OutputPrint a single integerΒ β€” the minimum number of actions needed to sort the railway cars.ExamplesInput54 1 2 5 3Output2Input44 1 3 2Output2NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.
Input54 1 2 5 3
Output2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1600']
B. More Cowbelltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≀ i ≀ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≀ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.InputThe first line of the input contains two space-separated integers n and k (1 ≀ n ≀ 2Β·k ≀ 100 000), denoting the number of cowbells and the number of boxes, respectively.The next line contains n space-separated integers s1, s2, ..., sn (1 ≀ s1 ≀ s2 ≀ ... ≀ sn ≀ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.OutputPrint a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.ExamplesInput2 12 5Output7Input4 32 3 5 9Output9Input3 23 5 7Output8NoteIn the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.In the third sample, the optimal solution is {3, 5} and {7}.
Input2 12 5
Output7
2 seconds
256 megabytes
['binary search', 'greedy', '*1400']
A. Uncowed Forcestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is . His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.InputThe first line of the input contains five space-separated integers m1, m2, m3, m4, m5, where mi (0 ≀ mi ≀ 119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted.The second line contains five space-separated integers w1, w2, w3, w4, w5, where wi (0 ≀ wi ≀ 10) is Kevin's number of wrong submissions on problem i.The last line contains two space-separated integers hs and hu (0 ≀ hs, hu ≀ 20), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively.OutputPrint a single integer, the value of Kevin's final score.ExamplesInput20 40 60 80 1000 1 2 3 41 0Output4900Input119 119 119 119 1190 0 0 0 010 0Output4930NoteIn the second sample, Kevin takes 119 minutes on all of the problems. Therefore, he gets of the points on each problem. So his score from solving problems is . Adding in 10Β·100 = 1000 points from hacks, his total score becomes 3930 + 1000 = 4930.
Input20 40 60 80 1000 1 2 3 41 0
Output4900
1 second
256 megabytes
['implementation', '*1000']
E. Pastoral Odditiestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the land of Bovinia there are n pastures, but no paths connecting the pastures. Of course, this is a terrible situation, so Kevin Sun is planning to rectify it by constructing m undirected paths connecting pairs of distinct pastures. To make transportation more efficient, he also plans to pave some of these new paths.Kevin is very particular about certain aspects of path-paving. Since he loves odd numbers, he wants each pasture to have an odd number of paved paths connected to it. Thus we call a paving sunny if each pasture is incident to an odd number of paved paths. He also enjoys short paths more than long paths, so he would like the longest paved path to be as short as possible. After adding each path, Kevin wants to know if a sunny paving exists for the paths of Bovinia, and if at least one does, the minimum possible length of the longest path in such a paving. Note that "longest path" here means maximum-weight edge.InputThe first line contains two integers n (2 ≀ n ≀ 100 000) and m (1 ≀ m ≀ 300 000), denoting the number of pastures and paths, respectively. The next m lines each contain three integers ai, bi and li, describing the i-th path. The i-th path connects pastures ai and bi (1 ≀ ai, bi ≀ n; ai ≠ bi) and has length li (1 ≀ li ≀ 109). Paths are given in the order in which they are constructed. OutputOutput m lines. The i-th line should contain a single integer denoting the minimum possible length of the longest path (maximum-weight edge) in a sunny paving using only the first i paths. If Kevin cannot pave a set of paths so that each pasture is incident to an odd number of paved paths, output  - 1.Note that the paving is only hypotheticalβ€”your answer after adding the i-th path should not be affected by any of your previous answers.ExamplesInput4 41 3 42 4 81 2 23 4 3Output-1883Input3 21 2 32 3 4Output-1-1Input4 102 1 9873 2 8294 1 7684 2 6083 4 5933 2 4884 2 3342 1 2041 3 1141 4 39Output-1-1829829768768768488334204NoteFor the first sample, these are the paths that Kevin should pave after building the i-th path: No set of paths works. Paths 1 (length 4) and 2 (length 8). Paths 1 (length 4) and 2 (length 8). Paths 3 (length 2) and 4 (length 3). In the second sample, there never exists a paving that makes Kevin happy.
Input4 41 3 42 4 81 2 23 4 3
Output-1883
4 seconds
256 megabytes
['data structures', 'divide and conquer', 'dsu', 'math', 'trees', '*3000']
D. Ruminations on Ruminantstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKevin Sun is ruminating on the origin of cows while standing at the origin of the Cartesian plane. He notices n lines on the plane, each representable by an equation of the form ax + by = c. He also observes that no two lines are parallel and that no three lines pass through the same point.For each triple (i, j, k) such that 1 ≀ i < j < k ≀ n, Kevin considers the triangle formed by the three lines . He calls a triangle original if the circumcircle of that triangle passes through the origin. Since Kevin believes that the circles of bovine life are tied directly to such triangles, he wants to know the number of original triangles formed by unordered triples of distinct lines. Recall that the circumcircle of a triangle is the circle which passes through all the vertices of that triangle.InputThe first line of the input contains a single integer n (3 ≀ n ≀ 2000), the number of lines.The next n lines describe lines . The i-th of these lines contains three space-separated integers ai, bi, ci (|ai|, |bi|, |ci| ≀ 10 000, ai2 + bi2 > 0), representing the equation aix + biy = ci of line .OutputPrint a single integer, the number of triples (i, j, k) with i < j < k such that lines form an original triangle.ExamplesInput41 0 00 1 01 1 -11 -1 2Output2Input30 1 11 1 21 -1 -2Output1NoteNote that in the first sample, some of the lines pass through the origin.In the second sample, there is exactly one triple of lines: y = 1, x + y = 2, x - y =  - 2. The triangle they form has vertices (0, 2), (1, 1), ( - 1, 1). The circumcircle of this triangle has equation x2 + (y - 1)2 = 1. This indeed passes through (0, 0).
Input41 0 00 1 01 1 -11 -1 2
Output2
4 seconds
256 megabytes
['geometry', 'math', '*2900']
C. Lieges of Legendretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either: Remove a single cow from a chosen non-empty pile. Choose a pile of cows with even size 2Β·x (x > 0), and replace it with k piles of x cows each. The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.InputThe first line of the input contains two space-separated integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109).The second line contains n integers, a1, a2, ... an (1 ≀ ai ≀ 109) describing the initial state of the game. OutputOutput the name of the winning player, either "Kevin" or "Nicky" (without quotes).ExamplesInput2 13 4OutputKevinInput1 23OutputNickyNoteIn the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Input2 13 4
OutputKevin
2 seconds
256 megabytes
['games', 'math', '*2200']
B. Moodular Arithmetictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that for some function . (This equation should hold for any integer x in the range 0 to p - 1, inclusive.)It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7.InputThe input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number.OutputPrint a single integer, the number of distinct functions f modulo 109 + 7.ExamplesInput3 2Output3Input5 4Output25NoteIn the first sample, p = 3 and k = 2. The following functions work: f(0) = 0, f(1) = 1, f(2) = 2. f(0) = 0, f(1) = 2, f(2) = 1. f(0) = f(1) = f(2) = 0.
Input3 2
Output3
1 second
256 megabytes
['combinatorics', 'dfs and similar', 'dsu', 'math', 'number theory', '*1800']
A. Alternative Thinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiadβ€”'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substringβ€”that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.InputThe first line contains the number of questions on the olympiad n (1 ≀ n ≀ 100 000).The following line contains a binary string of length n representing Kevin's results on the USAICO. OutputOutput a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.ExamplesInput810000011Output5Input201Output2NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.
Input810000011
Output5
2 seconds
256 megabytes
['dp', 'greedy', 'math', '*1600']
B. Approximating a Constant Rangetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challengingΒ β€” but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data pointsΒ β€” for each 1 ≀ i < n, it's guaranteed that |ai + 1 - ai| ≀ 1.A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≀ i ≀ r; the range [l, r] is almost constant if M - m ≀ 1.Find the length of the longest almost constant range.InputThe first line of the input contains a single integer n (2 ≀ n ≀ 100 000)Β β€” the number of data points.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 100 000).OutputPrint a single numberΒ β€” the maximum length of an almost constant range of the given sequence.ExamplesInput51 2 3 3 2Output4Input115 4 5 5 6 7 8 8 8 7 6Output5NoteIn the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
Input51 2 3 3 2
Output4
2 seconds
256 megabytes
['dp', 'implementation', 'two pointers', '*1400']
A. Two Basestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.InputThe first line of the input contains two space-separated integers n and bx (1 ≀ n ≀ 10, 2 ≀ bx ≀ 40), where n is the number of digits in the bx-based representation of X. The second line contains n space-separated integers x1, x2, ..., xn (0 ≀ xi < bx) β€” the digits of X. They are given in the order from the most significant digit to the least significant one.The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≀ m ≀ 10, 2 ≀ by ≀ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≀ yi < by) β€” the digits of Y.There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.OutputOutput a single character (quotes for clarity): '<' if X < Y '>' if X > Y '=' if X = Y ExamplesInput6 21 0 1 1 1 12 104 7Output=Input3 31 0 22 52 4Output<Input7 1615 15 4 0 0 7 107 94 8 0 3 1 5 0Output>NoteIn the first sample, X = 1011112 = 4710 = Y.In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.In the third sample, and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Input6 21 0 1 1 1 12 104 7
Output=
1 second
256 megabytes
['brute force', 'implementation', '*1100']
E. A Museum Robberytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere's a famous museum in the city where KleofΓ‘Ε‘ lives. In the museum, n exhibits (numbered 1 through n) had been displayed for a long time; the i-th of those exhibits has value vi and mass wi. Then, the museum was bought by a large financial group and started to vary the exhibits. At about the same time, KleofΓ‘Ε‘... gained interest in the museum, so to say.You should process q events of three types: type 1 β€” the museum displays an exhibit with value v and mass w; the exhibit displayed in the i-th event of this type is numbered n + i (see sample explanation for more details) type 2 β€” the museum removes the exhibit with number x and stores it safely in its vault type 3 β€” KleofΓ‘Ε‘ visits the museum and wonders (for no important reason at all, of course): if there was a robbery and exhibits with total mass at most m were stolen, what would their maximum possible total value be?For each event of type 3, let s(m) be the maximum possible total value of stolen exhibits with total mass  ≀ m.Formally, let D be the set of numbers of all exhibits that are currently displayed (so initially D = {1, ..., n}). Let P(D) be the set of all subsets of D and let Then, s(m) is defined as Compute s(m) for each . Note that the output follows a special format.InputThe first line of the input contains two space-separated integers n and k (1 ≀ n ≀ 5000, 1 ≀ k ≀ 1000) β€” the initial number of exhibits in the museum and the maximum interesting mass of stolen exhibits. Then, n lines follow. The i-th of them contains two space-separated positive integers vi and wi (1 ≀ vi ≀ 1 000 000, 1 ≀ wi ≀ 1000)Β β€” the value and mass of the i-th exhibit.The next line contains a single integer q (1 ≀ q ≀ 30 000)Β β€” the number of events.Each of the next q lines contains the description of one event in the following format: 1 v w β€” an event of type 1, a new exhibit with value v and mass w has been added (1 ≀ v ≀ 1 000 000, 1 ≀ w ≀ 1000) 2 x β€” an event of type 2, the exhibit with number x has been removed; it's guaranteed that the removed exhibit had been displayed at that time 3 β€” an event of type 3, KleofΓ‘Ε‘ visits the museum and asks his questionThere will be at most 10 000 events of type 1 and at least one event of type 3.OutputAs the number of values s(m) can get large, output the answers to events of type 3 in a special format.For each event of type 3, consider the values s(m) computed for the question that KleofΓ‘Ε‘ asked in this event; print one line containing a single number where p = 107 + 19 and q = 109 + 7.Print the answers to events of type 3 in the order in which they appear in the input.ExamplesInput3 1030 460 65 1931 42 51 20 332 22 431 40 63Output556674384168191145947033915181541912Input3 1000100 42100 47400 1542 22 12 33Output0NoteIn the first sample, the numbers of displayed exhibits and values s(1), ..., s(10) for individual events of type 3 are, in order: The values of individual exhibits are v1 = 30, v2 = 60, v3 = 5, v4 = 42, v5 = 20, v6 = 40 and their masses are w1 = 4, w2 = 6, w3 = 1, w4 = 5, w5 = 3, w6 = 6.In the second sample, the only question is asked after removing all exhibits, so s(m) = 0 for any m.
Input3 1030 460 65 1931 42 51 20 332 22 431 40 63
Output556674384168191145947033915181541912
2 seconds
256 megabytes
['data structures', 'dp', '*2800']
D. Acyclic Organic Compoundstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of distinct strings which can be read this way as . Also, there's a number cv assigned to each vertex v. We are interested in vertices with the maximum value of .You should compute two statistics: the maximum value of and the number of vertices v with the maximum .InputThe first line of the input contains one integer n (1 ≀ n ≀ 300 000)Β β€” the number of vertices of the tree.The second line contains n space-separated integers ci (0 ≀ ci ≀ 109).The third line contains a string s consisting of n lowercase English lettersΒ β€” the i-th character of this string is the letter in vertex i.The following n - 1 lines describe the tree T. Each of them contains two space-separated integers u and v (1 ≀ u, v ≀ n) indicating an edge between vertices u and v.It's guaranteed that the input will describe a tree.OutputPrint two lines. On the first line, print over all 1 ≀ i ≀ n. On the second line, print the number of vertices v for which .ExamplesInput101 2 7 20 20 30 40 50 50 50cacabbcddd1 26 87 26 25 45 93 102 52 3Output513Input60 2 4 1 1 1raaaba1 22 32 42 53 6Output62NoteIn the first sample, the tree looks like this: The sets of strings that can be read from individual vertices are: Finally, the values of are: In the second sample, the values of are (5, 4, 2, 1, 1, 1). The distinct strings read in T2 are ; note that can be read down to vertices 3 or 4.
Input101 2 7 20 20 30 40 50 50 50cacabbcddd1 26 87 26 25 45 93 102 52 3
Output513
3 seconds
512 megabytes
['data structures', 'dfs and similar', 'dsu', 'hashing', 'strings', 'trees', '*2400']
C. KleofΓ‘Ε‘ and the n-thlontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKleofΓ‘Ε‘ is participating in an n-thlon - a tournament consisting of n different competitions in n different disciplines (numbered 1 through n). There are m participants in the n-thlon and each of them participates in all competitions.In each of these n competitions, the participants are given ranks from 1 to m in such a way that no two participants are given the same rank - in other words, the ranks in each competition form a permutation of numbers from 1 to m. The score of a participant in a competition is equal to his/her rank in it.The overall score of each participant is computed as the sum of that participant's scores in all competitions.The overall rank of each participant is equal to 1 + k, where k is the number of participants with strictly smaller overall score.The n-thlon is over now, but the results haven't been published yet. KleofΓ‘Ε‘ still remembers his ranks in each particular competition; however, he doesn't remember anything about how well the other participants did. Therefore, KleofΓ‘Ε‘ would like to know his expected overall rank.All competitors are equally good at each discipline, so all rankings (permutations of ranks of everyone except KleofΓ‘Ε‘) in each competition are equiprobable.InputThe first line of the input contains two space-separated integers n (1 ≀ n ≀ 100) and m (1 ≀ m ≀ 1000)Β β€” the number of competitions and the number of participants respectively.Then, n lines follow. The i-th of them contains one integer xi (1 ≀ xi ≀ m)Β β€” the rank of KleofΓ‘Ε‘ in the i-th competition.OutputOutput a single real number – the expected overall rank of KleofΓ‘Ε‘. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput4 102121Output1.0000000000000000Input5 512345Output2.7500000000000000Input3 6242Output1.6799999999999999NoteIn the first sample, KleofΓ‘Ε‘ has overall score 6. Nobody else can have overall score less than 6 (but it's possible for one other person to have overall score 6 as well), so his overall rank must be 1.
Input4 102121
Output1.0000000000000000
1 second
256 megabytes
['dp', 'math', 'probabilities', '*2300']
B. Lipshitz Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA function is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≀ KΒ·|x - y| holds for all . We'll deal with a more... discrete version of this term.For an array , we define it's Lipschitz constant as follows: if n < 2, if n β‰₯ 2, over all 1 ≀ i < j ≀ n In other words, is the smallest non-negative integer such that |h[i] - h[j]| ≀ LΒ·|i - j| holds for all 1 ≀ i, j ≀ n.You are given an array of size n and q queries of the form [l, r]. For each query, consider the subarray ; determine the sum of Lipschitz constants of all subarrays of .InputThe first line of the input contains two space-separated integers n and q (2 ≀ n ≀ 100 000 and 1 ≀ q ≀ 100)Β β€” the number of elements in array and the number of queries respectively.The second line contains n space-separated integers ().The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1 ≀ li < ri ≀ n).OutputPrint the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integerΒ β€” the sum of Lipschitz constants of all subarrays of .ExamplesInput10 41 5 2 9 1 3 4 2 1 72 43 87 101 9Output178223210Input7 65 7 7 4 6 6 21 22 32 61 74 73 5Output202259168NoteIn the first query of the first sample, the Lipschitz constants of subarrays of with length at least 2 are: The answer to the query is their sum.
Input10 41 5 2 9 1 3 4 2 1 72 43 87 101 9
Output178223210
1 second
256 megabytes
['data structures', 'math', '*2100']
A. The Two Routestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road networkΒ β€” for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safetyΒ β€” in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.InputThe first line of the input contains two integers n and m (2 ≀ n ≀ 400, 0 ≀ m ≀ n(n - 1) / 2)Β β€” the number of towns and the number of railways respectively.Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≀ u, v ≀ n, u ≠ v).You may assume that there is at most one railway connecting any two towns.OutputOutput one integerΒ β€” the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.ExamplesInput4 21 33 4Output2Input4 61 21 31 42 32 43 4Output-1Input5 54 23 54 55 11 2Output3NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Input4 21 33 4
Output2
2 seconds
256 megabytes
['graphs', 'shortest paths', '*1600']
F. Edge coloring of bipartite graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour.InputThe first line contains three integers a, b, m (1 ≀ a, b ≀ 1000, 0 ≀ m ≀ 105), a is the size of the first part, b is the size of the second part, m is the number of edges in the graph.Each of the next m lines contains two integers x, y (1 ≀ x ≀ a, 1 ≀ y ≀ b), where x is the number of the vertex in the first part and y is the number of the vertex in the second part. It is guaranteed that there are no multiple edges.OutputIn the first line print integer c β€” the minimal number of colours. The second line should contain m integers from 1 to c β€” the colours of the edges (in the order they appear in the input).If there are several solutions, you can print any one of them.ExamplesInput4 3 51 22 23 24 14 3Output31 2 3 1 2
Input4 3 51 22 23 24 14 3
Output31 2 3 1 2
1 second
256 megabytes
['graphs', '*2800']
E. Lomsat gelraltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.For each vertex v find the sum of all dominating colours in the subtree of vertex v.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of vertices in the tree.The second line contains n integers ci (1 ≀ ci ≀ n), ci β€” the colour of the i-th vertex.Each of the next n - 1 lines contains two integers xj, yj (1 ≀ xj, yj ≀ n) β€” the edge of the tree. The first vertex is the root of the tree.OutputPrint n integers β€” the sums of dominating colours for each vertex.ExamplesInput41 2 3 41 22 32 4Output10 9 3 4Input151 2 3 1 2 3 3 1 1 3 2 2 1 2 31 21 31 41 141 152 52 62 73 83 93 104 114 124 13Output6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Input41 2 3 41 22 32 4
Output10 9 3 4
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'trees', '*2300']
D. Area of Two Circles' Intersectiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two circles. Find the area of their intersection.InputThe first line contains three integers x1, y1, r1 ( - 109 ≀ x1, y1 ≀ 109, 1 ≀ r1 ≀ 109) β€” the position of the center and the radius of the first circle.The second line contains three integers x2, y2, r2 ( - 109 ≀ x2, y2 ≀ 109, 1 ≀ r2 ≀ 109) β€” the position of the center and the radius of the second circle.OutputPrint the area of the intersection of the circles. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.ExamplesInput0 0 46 0 4Output7.25298806364175601379Input0 0 511 0 5Output0.00000000000000000000
Input0 0 46 0 4
Output7.25298806364175601379
2 seconds
256 megabytes
['geometry', '*2000']
C. Make Palindrometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.InputThe only line contains string s (1 ≀ |s| ≀ 2Β·105) consisting of only lowercase Latin letters.OutputPrint the lexicographically smallest palindrome that can be obtained with the minimal number of changes.ExamplesInputaabcOutputabbaInputaabcdOutputabcba
Inputaabc
Outputabba
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*1800']
B. Queries about less or equal elementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the sizes of arrays a and b.The second line contains n integers β€” the elements of array a ( - 109 ≀ ai ≀ 109).The third line contains m integers β€” the elements of array b ( - 109 ≀ bj ≀ 109).OutputPrint m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.ExamplesInput5 41 3 5 7 96 4 2 8Output3 2 1 4Input5 51 2 1 2 53 1 4 1 5Output4 2 4 2 5
Input5 41 3 5 7 96 4 2 8
Output3 2 1 4
2 seconds
256 megabytes
['binary search', 'data structures', 'sortings', 'two pointers', '*1300']
A. Extract Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".InputThe only line of input contains the string s (1 ≀ |s| ≀ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.OutputPrint the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34).If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.ExamplesInputaba,123;1a;0Output"123,0""aba,1a"Input1;;01,a0,Output"1"",01,a0,"Input1Output"1"-InputaOutput-"a"NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Inputaba,123;1a;0
Output"123,0""aba,1a"
2 seconds
256 megabytes
['implementation', 'strings', '*1600']
E. Sandy and Nutstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRooted tree is a connected graph without any simple cycles with one vertex selected as a root. In this problem the vertex number 1 will always serve as a root.Lowest common ancestor of two vertices u and v is the farthest from the root vertex that lies on both the path from u to the root and on path from v to the root. We will denote it as LCA(u, v).Sandy had a rooted tree consisting of n vertices that she used to store her nuts. Unfortunately, the underwater storm broke her tree and she doesn't remember all it's edges. She only managed to restore m edges of the initial tree and q triples ai, bi and ci, for which she supposes LCA(ai, bi) = ci.Help Sandy count the number of trees of size n with vertex 1 as a root, that match all the information she remembered. If she made a mess and there are no such trees then print 0. Two rooted trees are considered to be distinct if there exists an edge that occur in one of them and doesn't occur in the other one.InputThe first line of the input contains three integers n, m and q (1 ≀ n ≀ 13, 0 ≀ m < n, 0 ≀ q ≀ 100)Β β€” the number of vertices, the number of edges and LCA triples remembered by Sandy respectively.Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi)Β β€” the numbers of vertices connected by the i-th edge. It's guaranteed that this set of edges is a subset of edges of some tree.The last q lines contain the triplets of numbers ai, bi, ci (1 ≀ ai, bi, ci ≀ n). Each of these triples define LCA(ai, bi) = ci. It's not guaranteed that there exists a tree that satisfy all the given LCA conditions.OutputPrint a single integerΒ β€” the number of trees of size n that satisfy all the conditions.ExamplesInput4 0 0Output16Input4 0 13 4 2Output1Input3 1 01 2Output2Input3 0 22 3 22 3 1Output0Input4 1 21 22 2 23 4 2Output1NoteIn the second sample correct answer looks like this: In the third sample there are two possible trees: In the fourth sample the answer is 0 because the information about LCA is inconsistent.
Input4 0 0
Output16
3 seconds
256 megabytes
['bitmasks', 'dp', 'trees', '*2600']
D. Spongebob and Squarestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSpongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3 × 5 table is 15 + 8 + 3 = 26.InputThe first line of the input contains a single integer x (1 ≀ x ≀ 1018)Β β€” the number of squares inside the tables Spongebob is interested in.OutputFirst print a single integer kΒ β€” the number of tables with exactly x distinct squares inside.Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equalityΒ β€” in the order of increasing m.ExamplesInput26Output61 262 93 55 39 226 1Input2Output21 22 1Input8Output41 82 33 28 1NoteIn a 1 × 2 table there are 2 1 × 1 squares. So, 2 distinct squares in total. In a 2 × 3 table there are 6 1 × 1 squares and 2 2 × 2 squares. That is equal to 8 squares in total.
Input26
Output61 262 93 55 39 226 1
2 seconds
256 megabytes
['brute force', 'math', '*1900']
C. Day at the Beachtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to hi. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition hi ≀ hi + 1 holds for all i from 1 to n - 1.Squidward suggested the following process of sorting castles: Castles are split into blocksΒ β€” groups of consecutive castles. Therefore the block from i to j will include castles i, i + 1, ..., j. A block may consist of a single castle. The partitioning is chosen in such a way that every castle is a part of exactly one block. Each block is sorted independently from other blocks, that is the sequence hi, hi + 1, ..., hj becomes sorted. The partitioning should satisfy the condition that after each block is sorted, the sequence hi becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of castles Spongebob, Patrick and Squidward made from sand during the day.The next line contains n integers hi (1 ≀ hi ≀ 109). The i-th of these integers corresponds to the height of the i-th castle.OutputPrint the maximum possible number of blocks in a valid partitioning.ExamplesInput31 2 3Output3Input42 1 3 2Output2NoteIn the first sample the partitioning looks like that: [1][2][3]. In the second sample the partitioning is: [2, 1][3, 2]
Input31 2 3
Output3
2 seconds
256 megabytes
['sortings', '*1600']
B. Spongebob and Joketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n and for each number ai got number bi = fai. To finish the prank he erased the initial sequence ai.It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 100 000)Β β€” the lengths of sequences fi and bi respectively.The second line contains n integers, determining sequence f1, f2, ..., fn (1 ≀ fi ≀ n).The last line contains m integers, determining sequence b1, b2, ..., bm (1 ≀ bi ≀ n).OutputPrint "Possible" if there is exactly one sequence ai, such that bi = fai for all i from 1 to m. Then print m integers a1, a2, ..., am.If there are multiple suitable sequences ai, print "Ambiguity".If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print "Impossible".ExamplesInput3 33 2 11 2 3OutputPossible3 2 1 Input3 31 1 11 1 1OutputAmbiguityInput3 31 2 13 3 3OutputImpossibleNoteIn the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.In the third sample fi ≠ 3 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake.
Input3 33 2 11 2 3
OutputPossible3 2 1
2 seconds
256 megabytes
['implementation', '*1500']
A. Patrick and Shoppingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length d3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house. Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled.InputThe first line of the input contains three integers d1, d2, d3 (1 ≀ d1, d2, d3 ≀ 108)Β β€” the lengths of the paths. d1 is the length of the path connecting Patrick's house and the first shop; d2 is the length of the path connecting Patrick's house and the second shop; d3 is the length of the path connecting both shops. OutputPrint the minimum distance that Patrick will have to walk in order to visit both shops and return to his house.ExamplesInput10 20 30Output60Input1 1 5Output4NoteThe first sample is shown on the picture in the problem statement. One of the optimal routes is: house first shop second shop house.In the second sample one of the optimal routes is: house first shop house second shop house.
Input10 20 30
Output60
1 second
256 megabytes
['implementation', '*800']
F. Cut Lengthtime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.InputThe first line contains integers n and m (3 ≀ n ≀ 1000;1 ≀ m ≀ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.OutputPrint m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.ExamplesInput4 30 01 01 10 10 0 1 10 0 0 10 0 1 -1Output1.414213562373095145471.000000000000000000000.00000000000000000000
Input4 30 01 01 10 10 0 1 10 0 0 10 0 1 -1
Output1.414213562373095145471.000000000000000000000.00000000000000000000
0.5 seconds
256 megabytes
['geometry', '*2900']
E. Chocolate Bartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining nΒ·m - k squares are not necessarily form a single rectangular piece.InputThe first line of the input contains a single integer t (1 ≀ t ≀ 40910)Β β€” the number of values n, m and k to process.Each of the next t lines contains three integers n, m and k (1 ≀ n, m ≀ 30, 1 ≀ k ≀ min(nΒ·m, 50))Β β€” the dimensions of the chocolate bar and the number of squares you want to eat respectively.OutputFor each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.ExamplesInput42 2 12 2 32 2 22 2 4Output5540NoteIn the first query of the sample one needs to perform two breaks: to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4), to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1). In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
Input42 2 12 2 32 2 22 2 4
Output5540
2 seconds
256 megabytes
['brute force', 'dp', '*2000']
D. Igor In the Museumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor is in the museum and he wants to see as many pictures as possible.Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.InputFirst line of the input contains three integers n, m and k (3 ≀ n, m ≀ 1000, 1 ≀ k ≀ min(nΒ·m, 100 000))Β β€” the museum dimensions and the number of starting positions to process.Each of the next n lines contains m symbols '.', '*' β€” the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.Each of the last k lines contains two integers x and y (1 ≀ x ≀ n, 1 ≀ y ≀ m)Β β€” the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns β€” from left to right. It is guaranteed that all starting positions are empty cells.OutputPrint k integersΒ β€” the maximum number of pictures, that Igor can see if he starts in corresponding position.ExamplesInput5 6 3*******..*.********....*******2 22 54 3Output6410Input4 4 1*****..**.******3 2Output8
Input5 6 3*******..*.********....*******2 22 54 3
Output6410
1 second
256 megabytes
['dfs and similar', 'graphs', 'shortest paths', '*1700']
C. Nearest vectorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 and Ο€. For example, opposite directions vectors have angle equals to Ο€.InputFirst line of the input contains a single integer n (2 ≀ n ≀ 100 000)Β β€” the number of vectors.The i-th of the following n lines contains two integers xi and yi (|x|, |y| ≀ 10 000, x2 + y2 > 0)Β β€” the coordinates of the i-th vector. Vectors are numbered from 1 to n in order of appearing in the input. It is guaranteed that no two vectors in the input share the same direction (but they still can have opposite directions).OutputPrint two integer numbers a and b (a ≠ b)Β β€” a pair of indices of vectors with the minimal non-oriented angle. You can print the numbers in any order. If there are many possible answers, print any.ExamplesInput4-1 00 -11 01 1Output3 4Input6-1 00 -11 01 1-4 -5-4 -6Output6 5
Input4-1 00 -11 01 1
Output3 4
2 seconds
256 megabytes
['geometry', 'sortings', '*2300']
B. Queries on a Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1 = 3, r1 = 6, k1 = 1 then the answer is abbacaa. If after that we would process the query l2 = 1, r2 = 4, k2 = 2 then we would get the string baabcaa.InputThe first line of the input contains the string s (1 ≀ |s| ≀ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters.Second line contains a single integer m (1 ≀ m ≀ 300)Β β€” the number of queries.The i-th of the next m lines contains three integers li, ri and ki (1 ≀ li ≀ ri ≀ |s|, 1 ≀ ki ≀ 1 000 000)Β β€” the description of the i-th query.OutputPrint the resulting string s after processing all m queries.ExamplesInputabacaba23 6 11 4 2OutputbaabcaaNoteThe sample is described in problem statement.
Inputabacaba23 6 11 4 2
Outputbaabcaa
2 seconds
256 megabytes
['implementation', 'strings', '*1300']
A. Tricky Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.InputThe first line of the input contains a single integer t (1 ≀ t ≀ 100) β€” the number of values of n to be processed.Each of next t lines contains a single integer n (1 ≀ n ≀ 109).OutputPrint the requested sum for each of t integers n given in the input.ExamplesInput241000000000Output-4499999998352516354NoteThe answer for the first sample is explained in the statement.
Input241000000000
Output-4499999998352516354
1 second
256 megabytes
['math', '*900']
C. Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8Β·1018.InputFirst line contain two integer values n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 10) β€” the length of sequence and the number of elements in increasing subsequences.Next n lines contains one integer ai (1 ≀ ai ≀ n) each β€” elements of sequence. All values ai are different.OutputPrint one integer β€” the answer to the problem.ExamplesInput5 212354Output7
Input5 212354
Output7
1 second
256 megabytes
['data structures', 'dp', '*1900']
B. Restauranttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values β€” the start time li and the finish time ri (li ≀ ri).Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.InputThe first line contains integer number n (1 ≀ n ≀ 5Β·105) β€” number of orders. The following n lines contain integer values li and ri each (1 ≀ li ≀ ri ≀ 109).OutputPrint the maximal number of orders that can be accepted.ExamplesInput27 114 7Output1Input51 22 33 44 55 6Output3Input64 81 54 72 51 36 8Output2
Input27 114 7
Output1
4 seconds
256 megabytes
['dp', 'greedy', 'sortings', '*1600']
A. Divisibilitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFind the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≀ x ≀ b and x is divisible by k.InputThe only line contains three space-separated integers k, a and b (1 ≀ k ≀ 1018; - 1018 ≀ a ≀ b ≀ 1018).OutputPrint the required number.ExamplesInput1 1 10Output10Input2 -4 4Output5
Input1 1 10
Output10
1 second
256 megabytes
['math', '*1600']
E. Wilbur and Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWilbur the pig now wants to play with strings. He has found an n by m table consisting only of the digits from 0 to 9 where the rows are numbered 1 to n and the columns are numbered 1 to m. Wilbur starts at some square and makes certain moves. If he is at square (x, y) and the digit d (0 ≀ d ≀ 9) is written at position (x, y), then he must move to the square (x + ad, y + bd), if that square lies within the table, and he stays in the square (x, y) otherwise. Before Wilbur makes a move, he can choose whether or not to write the digit written in this square on the white board. All digits written on the whiteboard form some string. Every time a new digit is written, it goes to the end of the current string.Wilbur has q strings that he is worried about. For each string si, Wilbur wants to know whether there exists a starting position (x, y) so that by making finitely many moves, Wilbur can end up with the string si written on the white board.InputThe first line of the input consists of three integers n, m, and q (1 ≀ n, m, q ≀ 200)Β β€” the dimensions of the table and the number of strings to process, respectively.Each of the next n lines contains m digits from 0 and 9 giving the table itself.Then follow 10 lines. The i-th of them contains the values ai - 1 and bi - 1 ( - 200 ≀ ai, bi ≀ 200), i.e. the vector that Wilbur uses to make a move from the square with a digit i - 1 in it.There are q lines that follow. The i-th of them will contain a string si consisting only of digits from 0 to 9. It is guaranteed that the total length of these q strings won't exceed 1 000 000.OutputFor each of the q strings, print "YES" if Wilbur can choose x and y in order to finish with this string after some finite number of moves. If it's impossible, than print "NO" for the corresponding string.ExamplesInput1 1 201 11 11 11 11 11 11 11 11 11 100000000000002413423432432OutputYESNOInput4 2 5012345670 10 -10 10 -10 10 -10 10 -10 10 -1000000000001010101110132232232322443432223424443246767OutputYESYESYESNOYESNoteIn the first sample, there is a 1 by 1 table consisting of the only digit 0. The only move that can be made is staying on the square. The first string can be written on the white board by writing 0 repeatedly. The second string cannot be written as there is no 2 on the table.
Input1 1 201 11 11 11 11 11 11 11 11 11 100000000000002413423432432
OutputYESNO
3 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'strings', '*2500']
D. Wilbur and Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWilbur the pig really wants to be a beaver, so he decided today to pretend he is a beaver and bite at trees to cut them down.There are n trees located at various positions on a line. Tree i is located at position xi. All the given positions of the trees are distinct.The trees are equal, i.e. each tree has height h. Due to the wind, when a tree is cut down, it either falls left with probability p, or falls right with probability 1 - p. If a tree hits another tree while falling, that tree will fall in the same direction as the tree that hit it. A tree can hit another tree only if the distance between them is strictly less than h. For example, imagine there are 4 trees located at positions 1, 3, 5 and 8, while h = 3 and the tree at position 1 falls right. It hits the tree at position 3 and it starts to fall too. In it's turn it hits the tree at position 5 and it also starts to fall. The distance between 8 and 5 is exactly 3, so the tree at position 8 will not fall.As long as there are still trees standing, Wilbur will select either the leftmost standing tree with probability 0.5 or the rightmost standing tree with probability 0.5. Selected tree is then cut down. If there is only one tree remaining, Wilbur always selects it. As the ground is covered with grass, Wilbur wants to know the expected total length of the ground covered with fallen trees after he cuts them all down because he is concerned about his grass-eating cow friends. Please help Wilbur.InputThe first line of the input contains two integers, n (1 ≀ n ≀ 2000) and h (1 ≀ h ≀ 108) and a real number p (0 ≀ p ≀ 1), given with no more than six decimal places.The second line of the input contains n integers, x1, x2, ..., xn ( - 108 ≀ xi ≀ 108) in no particular order.OutputPrint a single real numberΒ β€” the expected total length of the ground covered by trees when they have all fallen down. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput2 2 0.5000001 2Output3.250000000Input4 3 0.44 3 1 2Output6.631200000NoteConsider the first example, we have 2 trees with height 2. There are 3 scenarios: 1. Both trees falls left. This can either happen with the right tree falling left first, which has probability (also knocking down the left tree), or the left tree can fall left and then the right tree can fall left, which has probability. Total probability is . 2. Both trees fall right. This is analogous to (1), so the probability of this happening is . 3. The left tree fall left and the right tree falls right. This is the only remaining scenario so it must have probability. Cases 1 and 2 lead to a total of 3 units of ground covered, while case 3 leads to a total of 4 units of ground covered. Thus, the expected value is .
Input2 2 0.5000001 2
Output3.250000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', 'sortings', '*2300']
C. Wilbur and Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≀ x' ≀ x and 0 ≀ y' ≀ y also belong to this set.Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x' β‰₯ x and y' β‰₯ y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4.Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x, y) = y - x. Now he gives Wilbur some w1, w2,..., wn, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to wi, that is s(xi, yi) = yi - xi = wi.Now Wilbur asks you to help him with this challenge.InputThe first line of the input consists of a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of points in the set Wilbur is playing with.Next follow n lines with points descriptions. Each line contains two integers x and y (0 ≀ x, y ≀ 100 000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0 ≀ x' ≀ x and 0 ≀ y' ≀ y, are also present in the input.The last line of the input contains n integers. The i-th of them is wi ( - 100 000 ≀ wi ≀ 100 000)Β β€” the required special value of the point that gets number i in any aesthetically pleasing numbering.OutputIf there exists an aesthetically pleasant numbering of points in the set, such that s(xi, yi) = yi - xi = wi, then print "YES" on the first line of the output. Otherwise, print "NO".If a solution exists, proceed output with n lines. On the i-th of these lines print the point of the set that gets number i. If there are multiple solutions, print any of them.ExamplesInput52 00 01 01 10 10 -1 -2 1 0OutputYES0 01 02 00 11 1Input31 00 02 00 1 2OutputNONoteIn the first sample, point (2, 0) gets number 3, point (0, 0) gets number one, point (1, 0) gets number 2, point (1, 1) gets number 5 and point (0, 1) gets number 4. One can easily check that this numbering is aesthetically pleasing and yi - xi = wi.In the second sample, the special values of the points in the set are 0,  - 1, and  - 2 while the sequence that the friend gives to Wilbur is 0, 1, 2. Therefore, the answer does not exist.
Input52 00 01 01 10 10 -1 -2 1 0
OutputYES0 01 02 00 11 1
2 seconds
256 megabytes
['combinatorics', 'greedy', 'sortings', '*1700']
B. Wilbur and Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the length of the array ai. Initially ai = 0 for every position i, so this array is not given in the input.The second line of the input contains n integers b1, b2, ..., bn ( - 109 ≀ bi ≀ 109).OutputPrint the minimum number of steps that Wilbur needs to make in order to achieve ai = bi for all i.ExamplesInput51 2 3 4 5Output5Input41 2 2 1Output3NoteIn the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1.
Input51 2 3 4 5
Output5
2 seconds
256 megabytes
['greedy', 'implementation', '*1100']
A. Wilbur and Swimming Pooltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 4)Β β€” the number of vertices that were not erased by Wilbur's friend.Each of the following n lines contains two integers xi and yi ( - 1000 ≀ xi, yi ≀ 1000)Β β€”the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order.It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes.OutputPrint the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print  - 1. ExamplesInput20 01 1Output1Input11 1Output-1NoteIn the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.
Input20 01 1
Output1
1 second
256 megabytes
['geometry', 'implementation', '*1100']
B. Pasha and Phonetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k + 1, k + 2, ..., 2Β·k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit bi and is divisible by ai if represented as an integer. To represent the block of length k as an integer, let's write it out as a sequence c1, c2,...,ck. Then the integer is calculated as the result of the expression c1Β·10k - 1 + c2Β·10k - 2 + ... + ck.Pasha asks you to calculate the number of good phone numbers of length n, for the given k, ai and bi. As this number can be too big, print it modulo 109 + 7. InputThe first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ min(n, 9))Β β€” the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k.The second line of the input contains n / k space-separated positive integersΒ β€” sequence a1, a2, ..., an / k (1 ≀ ai < 10k).The third line of the input contains n / k space-separated positive integersΒ β€” sequence b1, b2, ..., bn / k (0 ≀ bi ≀ 9). OutputPrint a single integerΒ β€” the number of good phone numbers of length n modulo 109 + 7.ExamplesInput6 238 56 497 3 4Output8Input8 21 22 3 445 4 3 2Output32400NoteIn the first test sample good phone numbers are: 000000, 000098, 005600, 005698, 380000, 380098, 385600, 385698.
Input6 238 56 497 3 4
Output8
1 second
256 megabytes
['binary search', 'math', '*1600']
A. Vitaly and Nighttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2Β·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2Β·m from left to right, then the j-th flat of the i-th floor has windows 2Β·j - 1 and 2Β·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 100)Β β€” the number of floors in the house and the number of flats on each floor respectively.Next n lines describe the floors from top to bottom and contain 2Β·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.OutputPrint a single integerΒ β€” the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.ExamplesInput2 20 0 0 11 0 1 1Output3Input1 31 1 0 1 0 0Output2NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.
Input2 20 0 0 11 0 1 1
Output3
1 second
256 megabytes
['constructive algorithms', 'implementation', '*800']
E. Cutting the Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a non-empty line s and an integer k. The following operation is performed with this line exactly once: A line is split into at most k non-empty substrings, i.e. string s is represented as a concatenation of a set of strings s = t1 + t2 + ... + tm, 1 ≀ m ≀ k. Some of strings ti are replaced by strings tir, that is, their record from right to left. The lines are concatenated back in the same order, we get string s' = t'1t'2... t'm, where t'i equals ti or tir. Your task is to determine the lexicographically smallest string that could be the result of applying the given operation to the string s.InputThe first line of the input contains string s (1 ≀ |s| ≀ 5 000 000), consisting of lowercase English letters. The second line contains integer k (1 ≀ k ≀ |s|)Β β€” the maximum number of parts in the partition.OutputIn the single line print the lexicographically minimum string s' which can be obtained as a result of performing the described operation. ExamplesInputaba2OutputaabInputaaaabacaba2OutputaaaaabacabInputbababa1OutputabababInputabacabadabacaba4Outputaababacabacabad
Inputaba2
Outputaab
2 seconds
256 megabytes
['string suffix structures', 'strings', '*3100']
D. REQtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday on a math lesson the teacher told Vovochka that the Euler function of a positive integer Ο†(n) is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number 1 is coprime to all the positive integers and Ο†(1) = 1.Now the teacher gave Vovochka an array of n positive integers a1, a2, ..., an and a task to process q queries li riΒ β€” to calculate and print modulo 109 + 7. As it is too hard for a second grade school student, you've decided to help Vovochka.InputThe first line of the input contains number n (1 ≀ n ≀ 200 000)Β β€” the length of the array given to Vovochka. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106).The third line contains integer q (1 ≀ q ≀ 200 000)Β β€” the number of queries. Next q lines contain the queries, one per line. Each query is defined by the boundaries of the segment li and ri (1 ≀ li ≀ ri ≀ n).OutputPrint q numbers β€” the value of the Euler function for each query, calculated modulo 109 + 7.ExamplesInput101 2 3 4 5 6 7 8 9 1071 13 85 64 88 107 97 10Output14608815361921441152Input724 63 13 52 6 10 163 54 71 72 43 62 6Output124876812939264112329984539136NoteIn the second sample the values are calculated like that: Ο†(13Β·52Β·6) = φ(4056) = 1248 Ο†(52Β·6Β·10Β·1) = φ(3120) = 768 Ο†(24Β·63Β·13Β·52Β·6Β·10Β·1) = φ(61326720) = 12939264 Ο†(63Β·13Β·52) = φ(42588) = 11232 Ο†(13Β·52Β·6Β·10) = φ(40560) = 9984 Ο†(63Β·13Β·52Β·6Β·10) = φ(2555280) = 539136
Input101 2 3 4 5 6 7 8 9 1071 13 85 64 88 107 97 10
Output14608815361921441152
3 seconds
256 megabytes
['data structures', 'number theory', '*2500']
C. Edo and Magnetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEdo has got a collection of n refrigerator magnets!He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers.Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of ​​the door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x1, y1) and the upper right corner (x2, y2), then its center is located at (, ) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.The sides of the refrigerator door must also be parallel to coordinate axes.InputThe first line contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ min(10, n - 1))Β β€” the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator.Next n lines describe the initial plan of placing magnets. Each line contains four integers x1, y1, x2, y2 (1 ≀ x1 < x2 ≀ 109, 1 ≀ y1 < y2 ≀ 109)Β β€” the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide.OutputPrint a single integerΒ β€” the minimum area of the door of refrigerator, which can be used to place at least n - k magnets, preserving the relative positions. ExamplesInput3 11 1 2 22 2 3 33 3 4 4Output1Input4 11 1 2 21 9 2 109 9 10 109 1 10 2Output64Input3 01 1 2 21 1 1000000000 10000000001 3 8 12Output249999999000000001NoteIn the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly.In the second test sample it doesn't matter which magnet to remove, the answer will not change β€” we need a fridge with door width 8 and door height 8.In the third sample you cannot remove anything as k = 0.
Input3 11 1 2 22 2 3 33 3 4 4
Output1
1 second
256 megabytes
['brute force', 'greedy', 'implementation', 'two pointers', '*2300']
B. Max and Biketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight line from point si to point fi (si < fi).Measuring time is a complex process related to usage of a special sensor and a time counter. Think of the front wheel of a bicycle as a circle of radius r. Let's neglect the thickness of a tire, the size of the sensor, and all physical effects. The sensor is placed on the rim of the wheel, that is, on some fixed point on a circle of radius r. After that the counter moves just like the chosen point of the circle, i.e. moves forward and rotates around the center of the circle.At the beginning each participant can choose any point bi, such that his bike is fully behind the starting line, that is, bi < si - r. After that, he starts the movement, instantly accelerates to his maximum speed and at time tsi, when the coordinate of the sensor is equal to the coordinate of the start, the time counter starts. The cyclist makes a complete ride, moving with his maximum speed and at the moment the sensor's coordinate is equal to the coordinate of the finish (moment of time tfi), the time counter deactivates and records the final time. Thus, the counter records that the participant made a complete ride in time tfi - tsi. Maxim is good at math and he suspects that the total result doesn't only depend on his maximum speed v, but also on his choice of the initial point bi. Now Maxim is asking you to calculate for each of n competitions the minimum possible time that can be measured by the time counter. The radius of the wheel of his bike is equal to r.InputThe first line contains three integers n, r and v (1 ≀ n ≀ 100 000, 1 ≀ r, v ≀ 109)Β β€” the number of competitions, the radius of the front wheel of Max's bike and his maximum speed, respectively. Next n lines contain the descriptions of the contests. The i-th line contains two integers si and fi (1 ≀ si < fi ≀ 109)Β β€” the coordinate of the start and the coordinate of the finish on the i-th competition.OutputPrint n real numbers, the i-th number should be equal to the minimum possible time measured by the time counter. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 6. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput2 1 21 105 9Output3.8496447105021.106060157705
Input2 1 21 105 9
Output3.8496447105021.106060157705
2 seconds
256 megabytes
['binary search', 'geometry', '*2500']
A. Warrior and Archertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x1, x2, ..., xn, two characters cannot end up at the same position.Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.InputThe first line on the input contains a single integer n (2 ≀ n ≀ 200 000, n is even)Β β€” the number of positions available initially. The second line contains n distinct integers x1, x2, ..., xn (0 ≀ xi ≀ 109), giving the coordinates of the corresponding positions.OutputPrint the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.ExamplesInput60 1 3 7 15 31Output7Input273 37Output36NoteIn the first sample one of the optimum behavior of the players looks like that: Vova bans the position at coordinate 15; Lesha bans the position at coordinate 3; Vova bans the position at coordinate 31; Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7.In the second sample there are only two possible positions, so there will be no bans.
Input60 1 3 7 15 31
Output7
2 seconds
256 megabytes
['games', '*2300']
E. Strange Calculation and Catstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGosha's universe is a table consisting of n rows and m columns. Both the rows and columns are numbered with consecutive integers starting with 1. We will use (r, c) to denote a cell located in the row r and column c.Gosha is often invited somewhere. Every time he gets an invitation, he first calculates the number of ways to get to this place, and only then he goes. Gosha's house is located in the cell (1, 1).At any moment of time, Gosha moves from the cell he is currently located in to a cell adjacent to it (two cells are adjacent if they share a common side). Of course, the movement is possible only if such a cell exists, i.e. Gosha will not go beyond the boundaries of the table. Thus, from the cell (r, c) he is able to make a move to one of the cells (r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1). Also, Ghosha can skip a move and stay in the current cell (r, c).Besides the love of strange calculations, Gosha is allergic to cats, so he never goes to the cell that has a cat in it. Gosha knows exactly where and when he will be invited and the schedule of cats travelling along the table. Formally, he has q records, the i-th of them has one of the following forms: 1, xi, yi, tiΒ β€” Gosha is invited to come to cell (xi, yi) at the moment of time ti. It is guaranteed that there is no cat inside cell (xi, yi) at this moment of time. 2, xi, yi, tiΒ β€” at the moment ti a cat appears in cell (xi, yi). It is guaranteed that no other cat is located in this cell (xi, yi) at that moment of time. 3, xi, yi, tiΒ β€” at the moment ti a cat leaves cell (xi, yi). It is guaranteed that there is cat located in the cell (xi, yi). Gosha plans to accept only one invitation, but he has not yet decided, which particular one. In order to make this decision, he asks you to calculate for each of the invitations i the number of ways to get to the cell (xi, yi) at the moment ti. For every invitation, assume that Gosha he starts moving from cell (1, 1) at the moment 1.Moving between two neighboring cells takes Gosha exactly one unit of tim. In particular, this means that Gosha can come into the cell only if a cat sitting in it leaves the moment when Gosha begins his movement from the neighboring cell, and if none of the cats comes to the cell at the time when Gosha is in it.Two ways to go from cell (1, 1) to cell (x, y) at time t are considered distinct if for at least one moment of time from 1 to t Gosha's positions are distinct for the two ways at this moment. Note, that during this travel Gosha is allowed to visit both (1, 1) and (x, y) multiple times. Since the number of ways can be quite large, print it modulo 109 + 7.InputThe first line of the input contains three positive integers n, m and q (1 ≀ nΒ·m ≀ 20, 1 ≀ q ≀ 10 000) β€” the number of rows and columns in the table and the number of events respectively.Next q lines describe the events, each description contains four integers tpi, xi, yi and ti (1 ≀ tp ≀ 3, 1 ≀ x ≀ n, 1 ≀ y ≀ m, 2 ≀ t ≀ 109)Β β€” the type of the event (1 if Gosha gets an invitation, 2 if a cat comes to the cell and 3 if a cat leaves the cell), the coordinates of the cell where the action takes place and the moment of time at which the action takes place respectively.It is guaranteed that the queries are given in the chronological order, i.e. ti < ti + 1. OutputFor each invitation i (that is, tpi = 1) calculate the number of ways to get to cell (xi, yi) at the moment of time ti. Respond to the invitations chronologically, that is, in the order they appear in the input.ExamplesInput1 3 32 1 2 33 1 2 51 1 1 7Output5Input3 3 32 2 2 21 3 3 51 3 3 7Output242Input4 5 52 2 5 32 2 4 63 2 4 91 4 4 131 4 4 15Output49090210598759NoteExplanation of the first sample. Each picture specifies the number of ways to arrive at the cell at the appropriate time. (X stands for a cell blocked at this particular moment of time) Time moment 1. Time moment 2. Time moment 3. Time moment 4. Time moment 5. Time moment 6. Time moment 7.
Input1 3 32 1 2 33 1 2 51 1 1 7
Output5
4 seconds
256 megabytes
['dp', 'matrices', '*2400']
D. Happy Tree Partytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBogdan has a birthday today and mom gave him a tree consisting of n vertecies. For every edge of the tree i, some number xi was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, m guests consecutively come to Bogdan's party. When the i-th guest comes, he performs exactly one of the two possible operations: Chooses some number yi, and two vertecies ai and bi. After that, he moves along the edges of the tree from vertex ai to vertex bi using the shortest path (of course, such a path is unique in the tree). Every time he moves along some edge j, he replaces his current number yi by , that is, by the result of integer division yi div xj. Chooses some edge pi and replaces the value written in it xpi by some positive integer ci < xpi. As Bogdan cares about his guests, he decided to ease the process. Write a program that performs all the operations requested by guests and outputs the resulting value yi for each i of the first type.InputThe first line of the input contains integers, n and m (2 ≀ n ≀ 200 000, 1 ≀ m ≀ 200 000)Β β€” the number of vertecies in the tree granted to Bogdan by his mom and the number of guests that came to the party respectively.Next n - 1 lines contain the description of the edges. The i-th of these lines contains three integers ui, vi and xi (1 ≀ ui, vi ≀ n, ui ≠ vi, 1 ≀ xi ≀ 1018), denoting an edge that connects vertecies ui and vi, with the number xi initially written on it.The following m lines describe operations, requested by Bogdan's guests. Each description contains three or four integers and has one of the two possible forms: 1 ai bi yi corresponds to a guest, who chooses the operation of the first type. 2 pi ci corresponds to a guests, who chooses the operation of the second type. It is guaranteed that all the queries are correct, namely 1 ≀ ai, bi ≀ n, 1 ≀ pi ≀ n - 1, 1 ≀ yi ≀ 1018 and 1 ≀ ci < xpi, where xpi represents a number written on edge pi at this particular moment of time that is not necessarily equal to the initial value xpi, as some decreases may have already been applied to it. The edges are numbered from 1 to n - 1 in the order they appear in the input.OutputFor each guest who chooses the operation of the first type, print the result of processing the value yi through the path from ai to bi.ExamplesInput6 61 2 11 3 71 4 42 5 52 6 21 4 6 172 3 21 4 6 171 5 5 202 4 11 5 1 3Output24203Input5 41 2 71 3 33 4 23 5 51 4 2 1001 5 4 12 2 21 1 3 4Output202NoteInitially the tree looks like this: The response to the first query is: = 2After the third edge is changed, the tree looks like this: The response to the second query is: = 4In the third query the initial and final vertex coincide, that is, the answer will be the initial number 20.After the change in the fourth edge the tree looks like this: In the last query the answer will be: = 3
Input6 61 2 11 3 71 4 42 5 52 6 21 4 6 172 3 21 4 6 171 5 5 202 4 11 5 1 3
Output24203
3 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'math', 'trees', '*2400']
C. Beautiful Functiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the imagined circles.Yesterday Ruslan tried to solve this problem for the case when the set of points is considered beautiful if it is given as (xt = f(t), yt = g(t)), where argument t takes all integer values from 0 to 50. Moreover, f(t) and g(t) should be correct functions.Assume that w(t) and h(t) are some correct functions, and c is an integer ranging from 0 to 50. The function s(t) is correct if it's obtained by one of the following rules: s(t) = abs(w(t)), where abs(x) means taking the absolute value of a number x, i.e. |x|; s(t) = (w(t) + h(t)); s(t) = (w(t) - h(t)); s(t) = (w(t) * h(t)), where  *  means multiplication, i.e. (w(t)Β·h(t)); s(t) = c; s(t) = t;Yesterday Ruslan thought on and on, but he could not cope with the task. Now he asks you to write a program that computes the appropriate f(t) and g(t) for any set of at most 50 circles.In each of the functions f(t) and g(t) you are allowed to use no more than 50 multiplications. The length of any function should not exceed 100Β·n characters. The function should not contain spaces.Ruslan can't keep big numbers in his memory, so you should choose f(t) and g(t), such that for all integer t from 0 to 50 value of f(t) and g(t) and all the intermediate calculations won't exceed 109 by their absolute value.InputThe first line of the input contains number n (1 ≀ n ≀ 50)Β β€” the number of circles Ruslan thinks of. Next follow n lines, each of them containing three integers xi, yi and ri (0 ≀ xi, yi ≀ 50, 2 ≀ ri ≀ 50)Β β€” the coordinates of the center and the raduis of the i-th circle.OutputIn the first line print a correct function f(t). In the second line print a correct function g(t). The set of the points (xt = f(t), yt = g(t)) (0 ≀ t ≀ 50) must satisfy the condition, that there is at least one point inside or on the border of each of the circles, Ruslan thinks of at the beginning.ExamplesInput30 10 410 0 420 10 4Outputt abs((t-10))NoteCorrect functions: 10 (1+2) ((t-3)+(t*4)) abs((t-10)) (abs((((23-t)*(t*t))+((45+12)*(t*t))))*((5*t)+((12*t)-13))) abs((t-(abs((t*31))+14))))Incorrect functions: 3+5+7 (not enough brackets, it should be ((3+5)+7) or (3+(5+7))) abs(t-3) (not enough brackets, it should be abs((t-3)) 2+(2-3 (one bracket too many) 1(t+5) (no arithmetic operation between 1 and the bracket) 5000*5000 (the number exceeds the maximum) The picture shows one of the possible solutions
Input30 10 410 0 420 10 4
Outputt abs((t-10))
2 seconds
256 megabytes
['constructive algorithms', 'math', '*2200']
B. Anton and Linestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = kiΒ·x + bi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1 < x2. In other words, is it true that there are 1 ≀ i < j ≀ n and x', y', such that: y' = ki * x' + bi, that is, point (x', y') belongs to the line number i; y' = kj * x' + bj, that is, point (x', y') belongs to the line number j; x1 < x' < x2, that is, point (x', y') lies inside the strip bounded by x1 < x2. You can't leave Anton in trouble, can you? Write a program that solves the given task.InputThe first line of the input contains an integer n (2 ≀ n ≀ 100 000)Β β€” the number of lines in the task given to Anton. The second line contains integers x1 and x2 ( - 1 000 000 ≀ x1 < x2 ≀ 1 000 000) defining the strip inside which you need to find a point of intersection of at least two lines.The following n lines contain integers ki, bi ( - 1 000 000 ≀ ki, bi ≀ 1 000 000)Β β€” the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two i ≠ j it is true that either ki ≠ kj, or bi ≠ bj.OutputPrint "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes).ExamplesInput41 21 21 00 10 2OutputNOInput21 31 0-1 3OutputYESInput21 31 00 2OutputYESInput21 31 00 3OutputNONoteIn the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it.
Input41 21 21 00 10 2
OutputNO
1 second
256 megabytes
['geometry', 'sortings', '*1600']
A. 2Chartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.InputThe first line of the input contains number n (1 ≀ n ≀ 100)Β β€” the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input.OutputPrint a single integerΒ β€” the maximum possible total length of words in Andrew's article.ExamplesInput4abbcaccaaabbbOutput9Input5aabcbcbcdecdecdecdecdecdeaaaaOutput6NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}.
Input4abbcaccaaabbb
Output9
2 seconds
256 megabytes
['brute force', 'implementation', '*1200']
E. BCPCtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBCPC stands for Byteforces Collegiate Programming Contest, and is the most famous competition in Byteforces.BCPC is a team competition. Each team is composed by a coach and three contestants. Blenda is the coach of the Bit State University(BSU), and she is very strict selecting the members of her team. In BSU there are n students numbered from 1 to n. Since all BSU students are infinitely smart, the only important parameters for Blenda are their reading and writing speed. After a careful measuring, Blenda have found that the i-th student have a reading speed equal to ri (words per minute), and a writing speed of wi (symbols per minute). Since BSU students are very smart, the measured speeds are sometimes very big and Blenda have decided to subtract some constant value c from all the values of reading speed and some value d from all the values of writing speed. Therefore she considers ri' = ri - c and wi' = wi - d. The student i is said to overwhelm the student j if and only if ri'Β·wj' > rj'Β·wi'. Blenda doesn’t like fights in teams, so she thinks that a team consisting of three distinct students i, j and k is good if i overwhelms j, j overwhelms k, and k overwhelms i. Yes, the relation of overwhelming is not transitive as it often happens in real life.Since Blenda is busy preparing a training camp in Codeforces, you are given a task to calculate the number of different good teams in BSU. Two teams are considered to be different if there is at least one student that is present in one team but is not present in the other. In other words, two teams are different if the sets of students that form these teams are different.InputIn the first line of the input three integers n, c and d (3 ≀ n ≀ 345678, 1 ≀ c, d ≀ 109) are written. They denote the number of students Blenda can use to form teams, the value subtracted from all reading speeds and the value subtracted from all writing speeds respectively.Each of the next n lines contains two integers ri and wi (0 < ri, wi ≀ 109, |ri - c| + |wi - d| > 0). There are no two students, such that both their reading and writing speeds coincide, i.e. for every i ≠ j condition |ri - rj| + |wi - wj| > 0 holds.OutputPrint the number of different teams in BSU, that are good according to Blenda's definition.ExamplesInput5 2 21 14 12 33 23 4Output4Input7 6 63 21 75 73 76 48 98 5Output11NoteIn the first sample the following teams are good: (i = 1, j = 2, k = 3), (i = 2, j = 5, k = 1), (i = 1, j = 4, k = 3), (i = 5, j = 1, k = 4).Note, that for example the team (i = 3, j = 1, k = 2) is also good, but is considered to be the same as the team (i = 1, j = 2, k = 3).
Input5 2 21 14 12 33 23 4
Output4
4 seconds
256 megabytes
['binary search', 'geometry', 'two pointers', '*2700']
D. Super Mtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAri the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.InputThe first line of the input contains two integers n and m (1 ≀ m ≀ n ≀ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively.Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≀ ui, vi ≀ n) - the ends of the road i.The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.OutputFirst print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number.Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons.Note that the correct answer is always unique.ExamplesInput7 21 21 31 43 53 63 72 7Output23Input6 41 22 32 44 54 62 4 5 6Output24NoteIn the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: and .However, you should choose the first one as it starts in the city with the lower number.
Input7 21 21 31 43 53 63 72 7
Output23
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*2200']
C. The Big Racetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L.Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today?InputThe first line of the input contains three integers t, w and b (1 ≀ t, w, b ≀ 5Β·1018) β€” the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively.OutputPrint the answer to the problem as an irreducible fraction . Follow the format of the samples output.The fraction (p and q are integers, and both p β‰₯ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d.ExamplesInput10 3 2Output3/10Input7 1 2Output3/7NoteIn the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
Input10 3 2
Output3/10
1 second
256 megabytes
['math', '*1800']
B. The Monster and the Squirreltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAri the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon. Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?InputThe first and only line of the input contains a single integer n (3 ≀ n ≀ 54321) - the number of vertices of the regular polygon drawn by Ari.OutputPrint the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.ExamplesInput5Output9Input3Output1NoteOne of the possible solutions for the first sample is shown on the picture above.
Input5
Output9
1 second
256 megabytes
['math', '*1100']
A. PawnChesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGalois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named Β«PawnChessΒ».This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed. Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.InputThe input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'. It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.OutputPrint 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.ExamplesInput.................B....B.....W.............W.....................OutputAInput..B.......W...........B..............W........B.................OutputBNoteIn the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Input.................B....B.....W.............W.....................
OutputA
1 second
256 megabytes
['implementation', '*1200']
B. Rebrandingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebrandingΒ β€” an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000)Β β€” the length of the initial name and the number of designers hired, respectively.The second line consists of n lowercase English letters and represents the original name of the corporation.Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.OutputPrint the new name of the corporation.ExamplesInput6 1policep mOutputmoliceInput11 6abacabadabaa bb ca de gf ab bOutputcdcbcdcfcdcNoteIn the second sample the name of the corporation consecutively changes as follows:
Input6 1policep m
Outputmolice
2 seconds
256 megabytes
['implementation', 'strings', '*1200']
A. Wizards' Dueltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.InputThe first line of the input contains a single integer l (1 ≀ l ≀ 1 000)Β β€” the length of the corridor where the fight takes place.The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500)Β β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.OutputPrint a single real numberΒ β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput1005050Output50Input1996040Output119.4NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.
Input1005050
Output50
2 seconds
256 megabytes
['implementation', 'math', '*900']
E. Birthdaytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputToday is birthday of a Little DashaΒ β€” she is now 8 years old! On this occasion, each of her n friends and relatives gave her a ribbon with a greeting written on it, and, as it turned out, all the greetings are different. Dasha gathered all the ribbons and decided to throw away some of them in order to make the remaining set stylish. The birthday girl considers a set of ribbons stylish if no greeting written on some ribbon is a substring of another greeting written on some other ribbon. Let us recall that the substring of the string s is a continuous segment of s.Help Dasha to keep as many ribbons as possible, so that she could brag about them to all of her friends. Dasha cannot rotate or flip ribbons, that is, each greeting can be read in a single way given in the input.InputThe first line of the input contains integer n (1 ≀ n ≀ 750)Β β€” the number of Dasha's relatives and friends.Each of the next n lines contains exactly one greeting. Each greeting consists of characters 'a' and 'b' only.The total length of all greetings won't exceed 10 000 000 characters.OutputIn the first line print the maximum size of the stylish set. In the second line print the numbers of ribbons involved in it, assuming that they are numbered from 1 to n in the order they appear in the input. If there are several stylish sets of the maximum size, print any of them.ExamplesInput5abababaaababababbbabOutput22 5NoteIn the sample, the answer that keeps ribbons 3 and 4 is also considered correct.
Input5abababaaababababbbab
Output22 5
3 seconds
512 megabytes
['graph matchings', 'strings', '*3200']
D. Top Secret Tasktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA top-secret military base under the command of Colonel Zuev is expecting an inspection from the Ministry of Defence. According to the charter, each top-secret military base must include a top-secret troop that should... well, we cannot tell you exactly what it should do, it is a top secret troop at the end. The problem is that Zuev's base is missing this top-secret troop for some reasons.The colonel decided to deal with the problem immediately and ordered to line up in a single line all n soldiers of the base entrusted to him. Zuev knows that the loquacity of the i-th soldier from the left is equal to qi. Zuev wants to form the top-secret troop using k leftmost soldiers in the line, thus he wants their total loquacity to be as small as possible (as the troop should remain top-secret). To achieve this, he is going to choose a pair of consecutive soldiers and swap them. He intends to do so no more than s times. Note that any soldier can be a participant of such swaps for any number of times. The problem turned out to be unusual, and colonel Zuev asked you to help.Determine, what is the minimum total loquacity of the first k soldiers in the line, that can be achieved by performing no more than s swaps of two consecutive soldiers.InputThe first line of the input contains three positive integers n, k, s (1 ≀ k ≀ n ≀ 150, 1 ≀ s ≀ 109)Β β€” the number of soldiers in the line, the size of the top-secret troop to be formed and the maximum possible number of swap operations of the consecutive pair of soldiers, respectively.The second line of the input contains n integer qi (1 ≀ qi ≀ 1 000 000)Β β€” the values of loquacity of soldiers in order they follow in line from left to right.OutputPrint a single integer β€” the minimum possible total loquacity of the top-secret troop.ExamplesInput3 2 22 4 1Output3Input5 4 210 1 6 2 5Output18Input5 2 33 1 4 2 5Output3NoteIn the first sample Colonel has to swap second and third soldiers, he doesn't really need the remaining swap. The resulting soldiers order is: (2, 1, 4). Minimum possible summary loquacity of the secret troop is 3. In the second sample Colonel will perform swaps in the following order: (10, 1, 6 β€” 2, 5) (10, 1, 2, 6 β€” 5) The resulting soldiers order is (10, 1, 2, 5, 6). Minimum possible summary loquacity is equal to 18.
Input3 2 22 4 1
Output3
3 seconds
256 megabytes
['dp', '*2300']
C. Three Statestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.InputThe first line of the input contains the dimensions of the map n and m (1 ≀ n, m ≀ 1000)Β β€” the number of rows and columns respectively.Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.OutputPrint a single integerΒ β€” the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.ExamplesInput4 511..2#..22#.323.#333Output2Input1 51#2#3Output-1
Input4 511..2#..22#.323.#333
Output2
5 seconds
512 megabytes
['dfs and similar', 'graphs', 'shortest paths', '*2200']
B. Chip 'n Dale Rescue Rangerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.InputThe first line of the input contains four integers x1, y1, x2, y2 (|x1|,  |y1|,  |x2|,  |y2| ≀ 10 000)Β β€” the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively. The second line contains two integers and t (0 < v, t ≀ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively. Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that and .OutputPrint a single real valueΒ β€” the minimum time the rescuers need to get to point (x2, y2). You answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput0 0 5 53 2-1 -1-1 0Output3.729935587093555327Input0 0 0 1000100 1000-50 050 0Output11.547005383792516398
Input0 0 5 53 2-1 -1-1 0
Output3.729935587093555327
1 second
256 megabytes
['binary search', 'geometry', 'math', '*2100']
A. Median Smoothingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm: b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence. For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1. The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.InputThe first input line of the input contains a single integer n (3 ≀ n ≀ 500 000)Β β€” the length of the initial sequence.The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.OutputIf the sequence will never become stable, print a single number  - 1.Otherwise, first print a single integerΒ β€” the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space Β β€” the resulting sequence itself.ExamplesInput40 0 1 1Output00 0 1 1Input50 1 0 1 0Output20 0 0 0 0NoteIn the second sample the stabilization occurs in two steps: , and the sequence 00000 is obviously stable.
Input40 0 1 1
Output00 0 1 1
2 seconds
256 megabytes
['implementation', '*1700']
B. Duff in Lovetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible.Malek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.InputThe first and only line of input contains one integer, n (1 ≀ n ≀ 1012).OutputPrint the answer in one line.ExamplesInput10Output10Input12Output6NoteIn first sample case, there are numbers 1, 2, 5 and 10 in the shop. 10 isn't divisible by any perfect square, so 10 is lovely.In second sample case, there are numbers 1, 2, 3, 4, 6 and 12 in the shop. 12 is divisible by 4 = 22, so 12 is not lovely, while 6 is indeed lovely.
Input10
Output10
2 seconds
256 megabytes
['math', '*1300']
A. Duff and Meattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ..., an and p1, ..., pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days. InputThe first line of input contains integer n (1 ≀ n ≀ 105), the number of days.In the next n lines, i-th line contains two integers ai and pi (1 ≀ ai, pi ≀ 100), the amount of meat Duff needs and the cost of meat in that day.OutputPrint the minimum money needed to keep Duff happy for n days, in one line.ExamplesInput31 32 23 1Output10Input31 32 13 2Output8NoteIn the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.
Input31 32 23 1
Output10
1 second
256 megabytes
['greedy', '*900']
F. Duff is Madtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuff is mad at her friends. That's why she sometimes makes Malek to take candy from one of her friends for no reason! She has n friends. Her i-th friend's name is si (their names are not necessarily unique). q times, she asks Malek to take candy from her friends. She's angry, but also she acts with rules. When she wants to ask Malek to take candy from one of her friends, like k, she chooses two numbers l and r and tells Malek to take exactly candies from him/her, where occur(t, s) is the number of occurrences of string t in s.Malek is not able to calculate how many candies to take in each request from Duff. That's why she asked for your help. Please tell him how many candies to take in each request.InputThe first line of input contains two integers n and q (1 ≀ n, q ≀ 105).The next n lines contain the names. i-th of them contains an string si, consisting of lowercase English letters ().The next q lines contain the requests. Each of them contains three integers, l, r and k (says that Malek should take candies from Duff's k-th friend).OutputPrint the answer to each request in one line.ExamplesInput5 5aababababababb1 5 43 5 41 5 21 5 31 4 1Output126371
Input5 5aababababababb1 5 43 5 41 5 21 5 31 4 1
Output126371
4 seconds
256 megabytes
['data structures', 'strings', '*3000']
E. Duff as a Queentime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuff is the queen of her country, Andarz Gu. She's a competitive programming fan. That's why, when he saw her minister, Malek, free, she gave her a sequence consisting of n non-negative integers, a1, a2, ..., an and asked him to perform q queries for her on this sequence. There are two types of queries: given numbers l, r and k, Malek should perform for each l ≀ i ≀ r (, bitwise exclusive OR of numbers a and b). given numbers l and r Malek should tell her the score of sequence al, al + 1, ... , ar. Score of a sequence b1, ..., bk is the number of its different Kheshtaks. A non-negative integer w is a Kheshtak of this sequence if and only if there exists a subsequence of b, let's denote it as bi1, bi2, ... , bix (possibly empty) such that (1 ≀ i1 < i2 < ... < ix ≀ k). If this subsequence is empty, then w = 0.Unlike Duff, Malek is not a programmer. That's why he asked for your help. Please help him perform these queries.InputThe first line of input contains two integers, n and q (1 ≀ n ≀ 2 × 105 and 1 ≀ q ≀ 4 × 104).The second line of input contains n integers, a1, a2, ..., an separated by spaces (0 ≀ ai ≀ 109 for each 1 ≀ i ≀ n).The next q lines contain the queries. Each line starts with an integer t (1 ≀ t ≀ 2), type of the corresponding query. If t = 1, then there are three more integers in that line, l, r and k. Otherwise there are two more integers, l and r. (1 ≀ l ≀ r ≀ n and 0 ≀ k ≀ 109)OutputPrint the answer of each query of the second type in one line.ExamplesInput5 51 2 3 4 22 1 51 2 2 82 1 51 1 3 102 2 2Output8161NoteIn the first query, we want all Kheshtaks of sequence 1, 2, 3, 4, 2 which are: 0, 1, 2, 3, 4, 5, 6, 7.In the third query, we want all Khestaks of sequence 1, 10, 3, 4, 2 which are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.In the fifth query, we want all Kheshtaks of sequence 0 which is 0.
Input5 51 2 3 4 22 1 51 2 2 82 1 51 1 3 102 2 2
Output8161
7 seconds
256 megabytes
['data structures', '*2900']
D. Duff in Mafiatime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuff is one if the heads of Mafia in her country, Andarz Gu. Andarz Gu has n cities (numbered from 1 to n) connected by m bidirectional roads (numbered by 1 to m).Each road has a destructing time, and a color. i-th road connects cities vi and ui and its color is ci and its destructing time is ti.Mafia wants to destruct a matching in Andarz Gu. A matching is a subset of roads such that no two roads in this subset has common endpoint. They can destruct these roads in parallel, i. e. the total destruction time is a maximum over destruction times of all selected roads. They want two conditions to be satisfied: The remaining roads form a proper coloring. Destructing time of this matching is minimized. The remaining roads after destructing this matching form a proper coloring if and only if no two roads of the same color have same endpoint, or, in the other words, edges of each color should form a matching.There is no programmer in Mafia. That's why Duff asked for your help. Please help her and determine which matching to destruct in order to satisfied those conditions (or state that this is not possible).InputThe first line of input contains two integers n and m (2 ≀ n ≀ 5 × 104 and 1 ≀ m ≀ 5 × 104), number of cities and number of roads in the country.The next m lines contain the the roads. i - th of them contains four integers vi, ui, ci and ti (1 ≀ vi, ui ≀ n, vi ≠ ui and 1 ≀ ci, ti ≀ 109 for each 1 ≀ i ≀ m).OutputIn the first line of input, print "Yes" (without quotes) if satisfying the first condition is possible and "No" (without quotes) otherwise.If it is possible, then you have to print two integers t and k in the second line, the minimum destructing time and the number of roads in the matching ().In the third line print k distinct integers separated by spaces, indices of the roads in the matching in any order. Roads are numbered starting from one in order of their appearance in the input.If there's more than one solution, print any of them.ExamplesInput5 72 1 3 73 1 1 65 4 1 84 5 1 13 2 2 34 5 2 52 3 2 4OutputYes3 24 5Input3 53 2 1 31 3 1 13 2 1 41 3 2 21 3 2 10OutputNoNoteGraph of Andarz Gu in the first sample case is as follows: A solution would be to destruct the roads with crosses.Graph of Andarz Gu in the second sample case is as follows:
Input5 72 1 3 73 1 1 65 4 1 84 5 1 13 2 2 34 5 2 52 3 2 4
OutputYes3 24 5
6 seconds
256 megabytes
['2-sat', 'binary search', '*3100']
C. Duff in the Armytime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently Duff has been a soldier in the army. Malek is her commander.Their country, Andarz Gu has n cities (numbered from 1 to n) and n - 1 bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.There are also m people living in Andarz Gu (numbered from 1 to m). Each person has and ID number. ID number of i - th person is i and he/she lives in city number ci. Note that there may be more than one person in a city, also there may be no people living in the city. Malek loves to order. That's why he asks Duff to answer to q queries. In each query, he gives her numbers v, u and a.To answer a query:Assume there are x people living in the cities lying on the path from city v to city u. Assume these people's IDs are p1, p2, ..., px in increasing order. If k = min(x, a), then Duff should tell Malek numbers k, p1, p2, ..., pk in this order. In the other words, Malek wants to know a minimums on that path (or less, if there are less than a people).Duff is very busy at the moment, so she asked you to help her and answer the queries.InputThe first line of input contains three integers, n, m and q (1 ≀ n, m, q ≀ 105).The next n - 1 lines contain the roads. Each line contains two integers v and u, endpoints of a road (1 ≀ v, u ≀ n, v ≠ u).Next line contains m integers c1, c2, ..., cm separated by spaces (1 ≀ ci ≀ n for each 1 ≀ i ≀ m).Next q lines contain the queries. Each of them contains three integers, v, u and a (1 ≀ v, u ≀ n and 1 ≀ a ≀ 10).OutputFor each query, print numbers k, p1, p2, ..., pk separated by spaces in one line.ExamplesInput5 4 51 31 21 44 52 1 4 34 5 61 5 25 5 102 3 35 3 1Output1 32 2 303 1 2 41 2NoteGraph of Andarz Gu in the sample case is as follows (ID of people in each city are written next to them):
Input5 4 51 31 21 44 52 1 4 34 5 61 5 25 5 102 3 35 3 1
Output1 32 2 303 1 2 41 2
4 seconds
512 megabytes
['data structures', 'trees', '*2200']
B. Duff in Beachtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denoted the remainder of dividing a by b. Duff is so curious, she wants to know the number of subsequences of b like bi1, bi2, ..., bix (0 ≀ i1 < i2 < ... < ix < l), such that: 1 ≀ x ≀ k For each 1 ≀ j ≀ x - 1, For each 1 ≀ j ≀ x - 1, bij ≀ bij + 1. i.e this subsequence is non-decreasing. Since this number can be very large, she want to know it modulo 109 + 7.Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.InputThe first line of input contains three integers, n, l and k (1 ≀ n, k, n × k ≀ 106 and 1 ≀ l ≀ 1018).The second line contains n space separated integers, a0, a1, ..., an - 1 (1 ≀ ai ≀ 109 for each 0 ≀ i ≀ n - 1). OutputPrint the answer modulo 1 000 000 007 in one line.ExamplesInput3 5 35 9 1Output10Input5 10 31 2 3 4 5Output25NoteIn the first sample case, . So all such sequences are: , , , , , , , , and .
Input3 5 35 9 1
Output10
2 seconds
256 megabytes
['dp', '*2100']
A. Duff and Weight Liftingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps. InputThe first line of input contains integer n (1 ≀ n ≀ 106), the number of weights.The second line contains n integers w1, ..., wn separated by spaces (0 ≀ wi ≀ 106 for each 1 ≀ i ≀ n), the powers of two forming the weights values.OutputPrint the minimum number of steps in a single line.ExamplesInput51 1 2 3 3Output2Input40 1 2 3Output4NoteIn the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.
Input51 1 2 3 3
Output2
1 second
256 megabytes
['greedy', '*1500']
B. Laurenty and Shoptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.The traffic light on the crosswalk from the j-th house of the i-th row to the (j + 1)-th house of the same row has waiting time equal to aij (1 ≀ i ≀ 2, 1 ≀ j ≀ n - 1). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals bj (1 ≀ j ≀ n). The city doesn't have any other crossings.The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing. Figure to the first sample. Help Laurenty determine the minimum total time he needs to wait at the crossroads.InputThe first line of the input contains integer n (2 ≀ n ≀ 50) β€” the number of houses in each row. Each of the next two lines contains n - 1 space-separated integer β€” values aij (1 ≀ aij ≀ 100). The last line contains n space-separated integers bj (1 ≀ bj ≀ 100).OutputPrint a single integer β€” the least total time Laurenty needs to wait at the crossroads, given that he crosses the avenue only once both on his way to the store and on his way back home.ExamplesInput41 2 33 2 13 2 2 3Output12Input31 23 32 1 3Output11Input2111 1Output4NoteThe first sample is shown on the figure above. In the second sample, Laurenty's path can look as follows: Laurenty crosses the avenue, the waiting time is 3; Laurenty uses the second crossing in the first row, the waiting time is 2; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty crosses the avenue, the waiting time is 1; Laurenty uses the second crossing in the second row, the waiting time is 3. In total we get that the answer equals 11.In the last sample Laurenty visits all the crossings, so the answer is 4.
Input41 2 33 2 13 2 2 3
Output12
1 second
256 megabytes
['implementation', '*1300']
A. Alena's Scheduletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlena has successfully passed the entrance exams to the university and is now looking forward to start studying.One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not.Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.InputThe first line of the input contains a positive integer n (1 ≀ n ≀ 100) β€” the number of lessons at the university. The second line contains n numbers ai (0 ≀ ai ≀ 1). Number ai equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a1, a2, ..., an are separated by spaces.OutputPrint a single number β€” the number of pairs during which Alena stays at the university.ExamplesInput50 1 0 1 1Output4Input71 0 1 0 0 1 0Output4Input10Output0NoteIn the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair. In the last sample Alena doesn't have a single pair, so she spends all the time at home.
Input50 1 0 1 1
Output4
1 second
256 megabytes
['implementation', '*900']
F. Digits of Number Pitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily has recently learned about the amazing properties of number Ο€. In one of the articles it has been hypothesized that, whatever the sequence of numbers we have, in some position, this sequence is found among the digits of number Ο€. Thus, if you take, for example, the epic novel "War and Peace" of famous Russian author Leo Tolstoy, and encode it with numbers, then we will find the novel among the characters of number Ο€.Vasily was absolutely delighted with this, because it means that all the books, songs and programs have already been written and encoded in the digits of Ο€. Vasily is, of course, a bit wary that this is only a hypothesis and it hasn't been proved, so he decided to check it out.To do this, Vasily downloaded from the Internet the archive with the sequence of digits of number Ο€, starting with a certain position, and began to check the different strings of digits on the presence in the downloaded archive. Vasily quickly found short strings of digits, but each time he took a longer string, it turned out that it is not in the archive. Vasily came up with a definition that a string of length d is a half-occurrence if it contains a substring of length of at least , which occurs in the archive.To complete the investigation, Vasily took 2 large numbers x, y (x ≀ y) with the same number of digits and now he wants to find the number of numbers in the interval from x to y, which are half-occurrences in the archive. Help Vasily calculate this value modulo 109 + 7.InputThe first line contains string s consisting of decimal digits (1 ≀ |s| ≀ 1000) that Vasily will use to search substrings in. According to hypothesis, this sequence of digis indeed occurs in the decimal representation of Ο€, although we can't guarantee that.The second and third lines contain two positive integers x, y of the same length d (x ≀ y, 2 ≀ d ≀ 50). Numbers x, y do not contain leading zeroes.OutputPrint how many numbers in the segment from x to y that are half-occurrences in s modulo 109 + 7.ExamplesInput021019Output2Input0234567891019Output9Input314159265351029Output20
Input021019
Output2
2 seconds
256 megabytes
['dp', 'implementation', 'strings', '*3200']
E. Present for Vitalik the Philatelist time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitalik the philatelist has a birthday today!As he is a regular customer in a stamp store called 'Robin Bobin', the store management decided to make him a gift.Vitalik wants to buy one stamp and the store will give him a non-empty set of the remaining stamps, such that the greatest common divisor (GCD) of the price of the stamps they give to him is more than one. If the GCD of prices of the purchased stamp and prices of present stamps set will be equal to 1, then Vitalik will leave the store completely happy.The store management asks you to count the number of different situations in which Vitalik will leave the store completely happy. Since the required number of situations can be very large, you need to find the remainder of this number modulo 109 + 7. The situations are different if the stamps purchased by Vitalik are different, or if one of the present sets contains a stamp that the other present does not contain.InputThe first line of the input contains integer n (2 ≀ n ≀ 5Β·105) β€” the number of distinct stamps, available for sale in the 'Robin Bobin' store. The second line contains a sequence of integers a1, a2, ..., an (2 ≀ ai ≀ 107), where ai is the price of the i-th stamp.OutputPrint a single integer β€” the remainder of the sought number of situations modulo 109 + 7.ExamplesInput32 3 2Output5Input29 6Output0NoteIn the first sample the following situations are possible: Vitalik buys the 1-st stamp, the store gives him the 2-nd stamp as a present; Vitalik buys the 3-rd stamp, the store gives him the 2-nd stamp as a present; Vitalik buys the 2-nd stamp, the store gives him the 1-st stamp as a present; Vitalik buys the 2-nd stamp, the store gives him the 3-rd stamp as a present; Vitalik buys the 2-nd stamp, the store gives him the 1-st and 3-rd stamps as a present.
Input32 3 2
Output5
5 seconds
256 megabytes
['combinatorics', 'math', 'number theory', '*2900']
D. Lizard Era: Beginningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions.The attitude of each of the companions to the hero is an integer. Initially, the attitude of each of them to the hero of neutral and equal to 0. As the hero completes quests, he makes actions that change the attitude of the companions, whom he took to perform this task, in positive or negative direction.Tell us what companions the hero needs to choose to make their attitude equal after completing all the quests. If this can be done in several ways, choose the one in which the value of resulting attitude is greatest possible.InputThe first line contains positive integer n (1 ≀ n ≀ 25) β€” the number of important tasks. Next n lines contain the descriptions of the tasks β€” the i-th line contains three integers li, mi, wi β€” the values by which the attitude of Lynn, Meliana and Worrigan respectively will change towards the hero if the hero takes them on the i-th task. All the numbers in the input are integers and do not exceed 107 in absolute value.OutputIf there is no solution, print in the first line "Impossible".Otherwise, print n lines, two characters is each line β€” in the i-th line print the first letters of the companions' names that hero should take to complete the i-th task ('L' for Lynn, 'M' for Meliana, 'W' for Worrigan). Print the letters in any order, if there are multiple solutions, print any of them.ExamplesInput31 0 00 1 00 0 1OutputLMMWMWInput70 8 95 9 -26 -8 -79 4 5-4 -9 9-4 5 2-6 8 -7OutputLMMWLMLWMWLMLWInput21 0 01 1 0OutputImpossible
Input31 0 00 1 00 0 1
OutputLMMWMW
2 seconds
256 megabytes
['meet-in-the-middle', '*2300']
C. Alice, Bob, Oranges and Applestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.InputThe first line of the input contains two integers, x, y (1 ≀ x, y ≀ 1018, xy > 1) β€” the number of oranges and apples that were initially in the bag.OutputPrint any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.ExamplesInput1 4Output3BInput2 2OutputImpossibleInput3 2Output1A1BNoteIn the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Input1 4
Output3B
1 second
256 megabytes
['number theory', '*2400']
B. Phillip and Trainstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe mobile application store has a new game called "Subway Roller".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column. InputEach test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≀ t ≀ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) β€” the number of sets.Then follows the description of t sets of the input data. The first line of the description of each set contains two integers n, k (2 ≀ n ≀ 100, 1 ≀ k ≀ 26) β€” the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.OutputFor each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.ExamplesInput216 4...AAAAA........s.BBB......CCCCC........DDDDD...16 4...AAAAA........s.BBB....CCCCC.........DDDDD....OutputYESNOInput210 4s.ZZ...........AAABB.YYYYYY...10 4s.ZZ..........AAAABB.YYYYYY...OutputYESNONoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset.
Input216 4...AAAAA........s.BBB......CCCCC........DDDDD...16 4...AAAAA........s.BBB....CCCCC.........DDDDD....
OutputYESNO
1 second
256 megabytes
['dfs and similar', 'graphs', 'shortest paths', '*1700']
A. Gennady the Dentisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one β€” by value vi - 1, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.InputThe first line of the input contains a positive integer n (1 ≀ n ≀ 4000) β€” the number of kids in the line. Next n lines contain three integers each vi, di, pi (1 ≀ vi, di, pi ≀ 106) β€” the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.OutputIn the first line print number k β€” the number of children whose teeth Gennady will cure.In the second line print k integers β€” the numbers of the children who will make it to the end of the line in the increasing order.ExamplesInput54 2 24 1 25 2 43 3 55 1 2Output21 3 Input54 5 15 3 94 1 22 1 84 1 9Output41 2 4 5 NoteIn the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to  - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5,  - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.
Input54 2 24 1 25 2 43 3 55 1 2
Output21 3
1 second
256 megabytes
['brute force', 'implementation', '*1800']
E. Anton and Iratime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.More formally, we have two permutations, p and s of numbers from 1 to n. We can swap pi and pj, by paying |i - j| coins for it. Find and print the smallest number of coins required to obtain permutation s from permutation p. Also print the sequence of swap operations at which we obtain a solution. InputThe first line contains a single number n (1 ≀ n ≀ 2000) β€” the length of the permutations.The second line contains a sequence of n numbers from 1 to n β€” permutation p. Each number from 1 to n occurs exactly once in this line.The third line contains a sequence of n numbers from 1 to n β€” permutation s. Each number from 1 to n occurs once in this line.OutputIn the first line print the minimum number of coins that you need to spend to transform permutation p into permutation s.In the second line print number k (0 ≀ k ≀ 2Β·106) β€” the number of operations needed to get the solution.In the next k lines print the operations. Each line must contain two numbers i and j (1 ≀ i, j ≀ n, i ≠ j), which means that you need to swap pi and pj.It is guaranteed that the solution exists.ExamplesInput44 2 1 33 2 4 1Output324 33 1NoteIn the first sample test we swap numbers on positions 3 and 4 and permutation p becomes 4 2 3 1. We pay |3 - 4| = 1 coins for that. On second turn we swap numbers on positions 1 and 3 and get permutation 3241 equal to s. We pay |3 - 1| = 2 coins for that. In total we pay three coins.
Input44 2 1 33 2 4 1
Output324 33 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*2300']
D. Dima and Lisatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.More formally, you are given an odd numer n. Find a set of numbers pi (1 ≀ i ≀ k), such that 1 ≀ k ≀ 3 pi is a prime The numbers pi do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.InputThe single line contains an odd number n (3 ≀ n < 109).OutputIn the first line print k (1 ≀ k ≀ 3), showing how many numbers are in the representation you found.In the second line print numbers pi in any order. If there are multiple possible solutions, you can print any of them.ExamplesInput27Output35 11 11NoteA prime is an integer strictly larger than one that is divisible only by one and by itself.
Input27
Output35 11 11
1 second
256 megabytes
['brute force', 'math', 'number theory', '*1800']
C. Marina and Vasyatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print  - 1.InputThe first line contains two integers n and t (1 ≀ n ≀ 105, 0 ≀ t ≀ n).The second line contains string s1 of length n, consisting of lowercase English letters.The third line contain string s2 of length n, consisting of lowercase English letters.OutputPrint a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.ExamplesInput3 2abcxycOutputaydInput1 0cbOutput-1
Input3 2abcxyc
Outputayd
1 second
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*1700']
B. Kolya and Tanya time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the circle by numbers from 0 to 3n - 1, let the gnome sitting on the i-th place have ai coins. If there is an integer i (0 ≀ i < n) such that ai + ai + n + ai + 2n ≠ 6, then Tanya is satisfied. Count the number of ways to choose ai so that Tanya is satisfied. As there can be many ways of distributing coins, print the remainder of this number modulo 109 + 7. Two ways, a and b, are considered distinct if there is index i (0 ≀ i < 3n), such that ai ≠ bi (that is, some gnome got different number of coins in these two ways).InputA single line contains number n (1 ≀ n ≀ 105) β€” the number of the gnomes divided by three.OutputPrint a single number β€” the remainder of the number of variants of distributing coins that satisfy Tanya modulo 109 + 7.ExamplesInput1Output20Input2Output680Note20 ways for n = 1 (gnome with index 0 sits on the top of the triangle, gnome 1 on the right vertex, gnome 2 on the left vertex):
Input1
Output20
1 second
256 megabytes
['combinatorics', '*1500']
A. Olesya and Rodiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print  - 1.InputThe single line contains two numbers, n and t (1 ≀ n ≀ 100, 2 ≀ t ≀ 10) β€” the length of the number and the number it should be divisible by.OutputPrint one such positive number without leading zeroes, β€” the answer to the problem, or  - 1, if such number doesn't exist. If there are multiple possible answers, you are allowed to print any of them.ExamplesInput3 2Output712
Input3 2
Output712
1 second
256 megabytes
['math', '*1000']
B. Robot's Tasktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRobot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.InputThe first line contains number n (1 ≀ n ≀ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≀ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.OutputPrint a single number β€” the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.ExamplesInput30 2 0Output1Input54 2 3 0 1Output3Input70 3 1 0 5 2 6Output2NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Input30 2 0
Output1
1 second
256 megabytes
['greedy', 'implementation', '*1200']
A. Asphalting Roadstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCity X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.InputThe first line contains integer n (1 ≀ n ≀ 50) β€” the number of vertical and horizontal roads in the city. Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi, vi (1 ≀ hi, vi ≀ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.OutputIn the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.ExamplesInput21 11 22 12 2Output1 4 Input11 1Output1 NoteIn the sample the brigade acts like that: On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road; On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything; On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything; On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road.
Input21 11 22 12 2
Output1 4
1 second
256 megabytes
['implementation', '*1000']
E. Boolean Functiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem we consider Boolean functions of four variables A, B, C, D. Variables A, B, C and D are logical and can take values 0 or 1. We will define a function using the following grammar:<expression> ::= <variable> | (<expression>) <operator> (<expression>)<variable> ::= 'A' | 'B' | 'C' | 'D' | 'a' | 'b' | 'c' | 'd'<operator> ::= '&' | '|'Here large letters A, B, C, D represent variables, and small letters represent their negations. For example, if A = 1, then character 'A' corresponds to value 1, and value character 'a' corresponds to value 0. Here character '&' corresponds to the operation of logical AND, character '|' corresponds to the operation of logical OR.You are given expression s, defining function f, where some operations and variables are missing. Also you know the values of the function f(A, B, C, D) for some n distinct sets of variable values. Count the number of ways to restore the elements that are missing in the expression so that the resulting expression corresponded to the given information about function f in the given variable sets. As the value of the result can be rather large, print its remainder modulo 109 + 7.InputThe first line contains expression s (1 ≀ |s| ≀ 500), where some characters of the operators and/or variables are replaced by character '?'. The second line contains number n (0 ≀ n ≀ 24) β€” the number of integers sets for which we know the value of function f(A, B, C, D). Next n lines contain the descriptions of the sets: the i-th of them contains five integers ai, bi, ci, di, ei (0 ≀ ai, bi, ci, di, ei ≀ 1), separated by spaces and meaning that f(ai, bi, ci, di) = ei. It is guaranteed that all the tuples (ai, bi, ci, di) are distinct.OutputIn a single line print the answer to the problem.ExamplesInput?21 0 1 0 10 1 1 0 1Output2Input(A)?(?)11 1 0 0 0Output4Input((?)&(?))|((?)&(?))0Output4096Inputb11 0 1 1 1Output1NoteIn the first sample the two valid expressions are 'C' and 'd'.In the second sample the expressions look as follows: '(A)&(a)', '(A)&(b)', '(A)&(C)', '(A)&(D)'.
Input?21 0 1 0 10 1 1 0 1
Output2
4 seconds
256 megabytes
['bitmasks', 'dp', 'expression parsing', '*3000']
D. Number of Binominal Coefficientstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a given prime integer p and integers Ξ±, A calculate the number of pairs of integers (n, k), such that 0 ≀ k ≀ n ≀ A and is divisible by pΞ±. As the answer can be rather large, print the remainder of the answer moduly 109 + 7.Let us remind you that is the number of ways k objects can be chosen from the set of n objects.InputThe first line contains two integers, p and Ξ± (1 ≀ p, α ≀ 109, p is prime). The second line contains the decimal record of integer A (0 ≀ A < 101000) without leading zeroes.OutputIn the single line print the answer to the problem.ExamplesInput2 27Output3Input3 19Output17Input3 39Output0Input2 45000Output8576851NoteIn the first sample three binominal coefficients divisible by 4 are , and .
Input2 27
Output3
4 seconds
256 megabytes
['dp', 'math', 'number theory', '*3300']