Problem ID stringlengths 2 6 | Problem Description stringlengths 139 10.6k | Rating float64 800 3.5k | Tags stringclasses 10 values | math bool 2 classes | greedy bool 2 classes | implementation bool 2 classes | dp bool 2 classes | data structures bool 2 classes | constructive algorithms bool 2 classes | brute force bool 2 classes | binary search bool 2 classes | sortings bool 2 classes | graphs bool 2 classes |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
987C | It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem. There are $$$n$$$ displays placed along a road, and the $$$i$$$-th of them can display a text with font size $$$s_i$$$ only. Maria Stepanovna wants to rent such three displays with indices $$$i < j < k$$$ that the font size increases if you move along the road in a particular direction. Namely, the condition $$$s_i < s_j < s_k$$$ should be held. The rent cost is for the $$$i$$$-th display is $$$c_i$$$. Please determine the smallest cost Maria Stepanovna should pay. Input The first line contains a single integer $$$n$$$ ($$$3 le n le 3,000$$$)xa0— the number of displays. The second line contains $$$n$$$ integers $$$s_1, s_2, ldots, s_n$$$ ($$$1 le s_i le 10^9$$$)xa0— the font sizes on the displays in the order they stand along the road. The third line contains $$$n$$$ integers $$$c_1, c_2, ldots, c_n$$$ ($$$1 le c_i le 10^8$$$)xa0— the rent costs for each display. Output If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integerxa0— the minimum total rent cost of three displays with indices $$$i < j < k$$$ such that $$$s_i < s_j < s_k$$$. Examples Input 5 2 4 5 4 10 40 30 20 10 40 Input 10 1 2 3 4 5 6 7 8 9 10 10 13 11 14 15 12 13 13 18 13 Note In the first example you can, for example, choose displays $$$1$$$, $$$4$$$ and $$$5$$$, because $$$s_1 < s_4 < s_5$$$ ($$$2 < 4 < 10$$$), and the rent cost is $$$40 + 10 + 40 = 90$$$. In the second example you can't select a valid triple of indices, so the answer is -1. | 1,400 | implementation | false | false | true | false | false | false | false | false | false | false |
1263A | You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day. Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies. Input The first line contains integer $$$t$$$ ($$$1 le t le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 le r, g, b le 10^8$$$) — the number of red, green and blue candies, respectively. Output Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input. Example Input 6 1 1 1 1 2 1 4 1 1 7 4 10 8 1 4 8 2 8 Note In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors. In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day. In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten. | 1,100 | math | true | false | false | false | false | false | false | false | false | false |
1089H | , # Problem A. Harder Satisfiability Time limit: 2 seconds A fully quantified boolean 2-CNF formula is a formula in the following form: Q1x1 . . . Q nxn F (x1, . . . , x n).Each Qi is one of two quantifiers: a universal quantifier 8 (“for all”), or an existential quantifier 9 (“exists”); and F is a conjunction (boolean AND ) of m clauses s _ t (boolean OR ), where s and t are some variables (not necessarily different) with or without negation. This formula has no free variables, so it evaluates to either true or false . We can evaluate a given fully quantified formula with a simple recursive algorithm: 1. If there are no quantifiers, return the remaining expression’s value of true or false .2. Otherwise, recursively evaluate formulas: Fz = Q2x2 . . . Q nxn F (z, x 2, . . . , x n) for z = 0 , 1.3. If Q1 = 9 return F0 _ F1; otherwise if Q1 = 8 return F0 ^ F1.You are given some fully quantified boolean 2-CNF formulas. Find out if they are true or not. # Input The first line of the input contains a single integer t (1 x14 t x14 10 5) — the number of test cases. The first line of a test case contains two integers n and m (1 x14 n, m x14 10 5) — the number of variables and the number of clauses in F . The next line contains a string s with n characters describing the quantifiers. If si = ‘A’ then Qi is a universal quantifier 8, otherwise if si = ‘E’ then si is an existential quantifier 9.Next m lines describe clauses in F . Each line contains two integers ui and vi (x00n x14 ui, v i x14 n; ui, v i̸ = 0 ). If ui x15 1 then the first variable in the i-th clause is xui . Otherwise, if ui x14 x00 1 then the first variable is x−ui (negation of x−ui ). The second variable in the i-th clause is similarly described by vi.The sum of values of n for all test cases does not exceed 10 5; the sum of values of m does not exceed 10 5. # Output For each test case output “ TRUE ” if the given formula is true or “ FALSE ” otherwise. # Example standard input standard output 32 2 AE 1 -2 -1 2 2 2 EA 1 -2 -1 2 3 2 AEA 1 -2 -1 -3 TRUE FALSE FALSE # Note The first sample corresponds to a formula 8x1 9x2 (x1 _ x2) ^ (x1 _ x2) = 8x1 9x2 x1 x08 x2. For any x1 we can choose x2 = x1 making it true, hence the formula is true. The second sample changes the order of quantifiers. Now the answer is “ FALSE ”, because for any value of x1 we can choose x2 = x1 and the formula becomes false. The third formula is 8x1 9x2 8x3 (x1 _ x2) ^ (x1 _ x3). If we substitute x1 = 1 , x3 = 1 then no assignment of x2 can make the second clause true, so the formula is false. Page 1 of 1 | 3,400 | graphs | false | false | false | false | false | false | false | false | false | true |
2030E | Suppose we partition the elements of an array $$$b$$$ into any number $$$k$$$ of non-empty multisets $$$S_1, S_2, ldots, S_k$$$, where $$$k$$$ is an arbitrary positive integer. Define the score of $$$b$$$ as the maximum value of $$$operatorname{MEX}(S_1)$$$$$$^{ ext{∗}}$$$$$$ + operatorname{MEX}(S_2) + ldots + operatorname{MEX}(S_k)$$$ over all possible partitions of $$$b$$$ for any integer $$$k$$$. Envy is given an array $$$a$$$ of size $$$n$$$. Since he knows that calculating the score of $$$a$$$ is too easy for you, he instead asks you to calculate the sum of scores of all $$$2^n - 1$$$ non-empty subsequences of $$$a$$$.$$$^{ ext{†}}$$$ Since this answer may be large, please output it modulo $$$998,244,353$$$. Input The first line contains an integer $$$t$$$ ($$$1 leq t leq 10^4$$$)xa0— the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 leq n leq 2 cdot 10^5$$$)xa0— the length of $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$0 leq a_i < n$$$)xa0— the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 cdot 10^5$$$. Output For each test case, output the answer, modulo $$$998,244,353$$$. Example Input 4 3 0 0 1 4 0 0 1 1 5 0 0 1 2 2 4 1 1 1 1 Note In the first testcase, we must consider seven subsequences: $$$[0]$$$: The score is $$$1$$$. $$$[0]$$$: The score is $$$1$$$. $$$[1]$$$: The score is $$$0$$$. $$$[0,0]$$$: The score is $$$2$$$. $$$[0,1]$$$: The score is $$$2$$$. $$$[0,1]$$$: The score is $$$2$$$. $$$[0,0,1]$$$: The score is $$$3$$$. The answer for the first testcase is $$$1+1+2+2+2+3=11$$$. In the last testcase, all subsequences have a score of $$$0$$$. | 2,200 | math | true | false | false | false | false | false | false | false | false | false |
1817B | You are given a simple undirected graph with $$$n$$$ nodes and $$$m$$$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $$$1$$$ to $$$n$$$. We define a graph to be a Fish Graph if it contains a simple cycle with a special node $$$u$$$ belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly $$$2$$$ extra edges. Both edges should connect to node $$$u$$$, but they should not be connected to any other node of the cycle. Determine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph. In this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph. Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph. Input The first line of input contains the integer $$$t$$$ ($$$1 leq t leq 1000$$$), the number of test cases. The description of test cases follows. The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$1 le n, m le 2,000$$$)xa0— the number of nodes and the number of edges. Each of the next $$$m$$$ lines contains the description of an edge. Each line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 leq u_i, v_i leq n$$$, $$$u_i eq v_i$$$)xa0— an edge connects node $$$u_i$$$ to node $$$v_i$$$. It is guaranteed that no two edges connect the same unordered pair of nodes. Furthermore, it is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases both do not exceed $$$2,000$$$. Output For each testcase, output "YES" if the graph contains a subgraph that is a Fish Graph, otherwise print "NO". If the answer is "YES", on the following lines output a description of the subgraph. The first line of the description contains one integer $$$k$$$ — the number of edges of the subgraph. On the next $$$k$$$ lines, output the edges of the chosen subgraph. Each of the $$$k$$$ lines should contains two integers $$$u$$$ and $$$v$$$ ($$$1le u, vle n$$$, $$$u eq v$$$) — the edge between $$$u$$$ and $$$v$$$ belongs to the subgraph. The order in which $$$u$$$ and $$$v$$$ are printed does not matter, as long as the two nodes are connected by an edge in the original graph. The order in which you print the edges does not matter, as long as the resulting subgraph is a fish graph. If there are multiple solutions, print any. Example Input 3 7 8 1 2 2 3 3 4 4 1 4 5 4 6 4 2 6 7 7 7 6 7 1 2 2 3 3 4 4 1 1 3 3 5 4 4 1 3 3 4 4 1 1 2 Output YES 6 5 4 6 4 4 3 1 4 2 1 3 2 YES 5 5 3 2 3 3 1 4 3 1 4 NO Note In the first example, a possible valid subgraph contains the cycle $$$1 ightarrow 2 ightarrow 3 ightarrow 4 ightarrow 1$$$. The special node of this cycle is node $$$4$$$. The two extra edges $$$4 - 5$$$ and $$$4 - 6$$$ are both connected to $$$4$$$, completing the Fish Graph. In the second example, a possible valid subgraph contains the cycle $$$1 ightarrow 3 ightarrow 4 ightarrow 1$$$. The special node of this cycle is node $$$3$$$. The two extra edges $$$3 - 2$$$ and $$$3 - 5$$$ are both connected to $$$3$$$, completing the Fish Graph. In the last example, it can be proven that there is no valid subgraph. | 1,900 | constructive algorithms | false | false | false | false | false | true | false | false | false | false |
45E | Vasya is a born Berland film director, he is currently working on a new blockbuster, "The Unexpected". Vasya knows from his own experience how important it is to choose the main characters' names and surnames wisely. He made up a list of _n_ names and _n_ surnames that he wants to use. Vasya haven't decided yet how to call characters, so he is free to match any name to any surname. Now he has to make the list of all the main characters in the following format: "_Name_1 _Surname_1, _Name_2 _Surname_2, ..., _Name__n_ _Surname__n_", i.e. all the name-surname pairs should be separated by exactly one comma and exactly one space, and the name should be separated from the surname by exactly one space. First of all Vasya wants to maximize the number of the pairs, in which the name and the surname start from one letter. If there are several such variants, Vasya wants to get the lexicographically minimal one. Help him. An answer will be verified a line in the format as is shown above, including the needed commas and spaces. It's the lexicographical minimality of such a line that needs to be ensured. The output line shouldn't end with a space or with a comma. Input The first input line contains number _n_ (1u2009≤u2009_n_u2009≤u2009100) — the number of names and surnames. Then follow _n_ lines — the list of names. Then follow _n_ lines — the list of surnames. No two from those 2_n_ strings match. Every name and surname is a non-empty string consisting of no more than 10 Latin letters. It is guaranteed that the first letter is uppercase and the rest are lowercase. Output The output data consist of a single line — the needed list. Note that one should follow closely the output data format! Examples Input 4 Ann Anna Sabrina John Petrov Ivanova Stoltz Abacaba Output Ann Abacaba, Anna Ivanova, John Petrov, Sabrina Stoltz Output Aa Ad, Ab Ae, Ac Bb, Ba Bc | 2,000 | greedy | false | true | false | false | false | false | false | false | false | false |
1388D | Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this... There are two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Initially, an $$$ans$$$ is equal to $$$0$$$ and the following operation is defined: 1. Choose position $$$i$$$ ($$$1 le i le n$$$); 2. Add $$$a_i$$$ to $$$ans$$$; 3. If $$$b_i eq -1$$$ then add $$$a_i$$$ to $$$a_{b_i}$$$. What is the maximum $$$ans$$$ you can get by performing the operation on each $$$i$$$ ($$$1 le i le n$$$) exactly once? Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them. Input The first line contains the integer $$$n$$$ ($$$1 le n le 2 cdot 10^5$$$)xa0— the length of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$−10^6 le a_i le 10^6$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, ldots, b_n$$$ ($$$1 le b_i le n$$$ or $$$b_i = -1$$$). Additional constraint: it's guaranteed that for any $$$i$$$ ($$$1 le i le n$$$) the sequence $$$b_i, b_{b_i}, b_{b_{b_i}}, ldots$$$ is not cyclic, in other words it will always end with $$$-1$$$. Output In the first line, print the maximum $$$ans$$$ you can get. In the second line, print the order of operations: $$$n$$$ different integers $$$p_1, p_2, ldots, p_n$$$ ($$$1 le p_i le n$$$). The $$$p_i$$$ is the position which should be chosen at the $$$i$$$-th step. If there are multiple orders, print any of them. Examples Input 10 -10 -1 2 2 5 -2 -3 -4 2 -6 -1 -1 2 2 -1 5 5 7 7 9 Output -9 3 5 6 1 9 4 10 7 8 2 | 2,000 | greedy | false | true | false | false | false | false | false | false | false | false |
123C | A two dimensional array is called a bracket array if each grid contains one of the two possible brackets — "(" or ")". A path through the two dimensional array cells is called monotonous if any two consecutive cells in the path are side-adjacent and each cell of the path is located below or to the right from the previous one. A two dimensional array whose size equals _n_u2009×u2009_m_ is called a correct bracket array, if any string formed by writing out the brackets on some monotonous way from cell (1,u20091) to cell (_n_,u2009_m_) forms a correct bracket sequence. Let's define the operation of comparing two correct bracket arrays of equal size (_a_ and _b_) like that. Let's consider a given two dimensional array of priorities (_c_) — a two dimensional array of same size, containing different integers from 1 to _nm_. Let's find such position (_i_,u2009_j_) in the two dimensional array, that _a__i_,u2009_j_u2009≠u2009_b__i_,u2009_j_. If there are several such positions, let's choose the one where number _c__i_,u2009_j_ is minimum. If _a__i_,u2009_j_u2009=u2009"(", then _a_u2009<u2009_b_, otherwise _a_u2009>u2009_b_. If the position (_i_,u2009_j_) is not found, then the arrays are considered equal. Your task is to find a _k_-th two dimensional correct bracket array. It is guaranteed that for the given sizes of _n_ and _m_ there will be no less than _k_ two dimensional correct bracket arrays. Input The first line contains integers _n_, _m_ and _k_ — the sizes of the array and the number of the sought correct bracket array (1u2009≤u2009_n_,u2009_m_u2009≤u2009100, 1u2009≤u2009_k_u2009≤u20091018). Then an array of priorities is given, _n_ lines each containing _m_ numbers, number _p__i_,u2009_j_ shows the priority of character _j_ in line _i_ (1u2009≤u2009_p__i_,u2009_j_u2009≤u2009_nm_, all _p__i_,u2009_j_ are different). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Note In the first sample exists only one correct two-dimensional bracket array. In the second and in the third samples two arrays exist. A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. | 2,300 | greedy | false | true | false | false | false | false | false | false | false | false |
1769D3 | В этой версии задачи нужно найти $$$26$$$ раскладов с различными значениями важности первого хода. Алиса и Боб решили сыграть в карточную игру «Девятка». Пожалуйста, внимательно прочитайте условие задачи, поскольку правила могут отличаться от известных вам. Для игры нужна стандартная колода из $$$36$$$ картxa0— по девять карт (от шестёрки до туза) каждой из четырёх мастей (трефы, бубны, пики и черви). Карты по достоинству от младшей к старшей идут следующим образом: шестёрка, семёрка, восьмёрка, девятка, десятка, валет, дама, король, туз. Перед игрой колода перемешивается, и каждому игроку раздаётся по $$$18$$$ карт. Карты нужно выкладывать из руки на стол по определённым правилам. Выигрывает игрок, который первым выложит все карты из своей руки. Игроки ходят по очереди. Ход игрока имеет один из следующих видов: выложить на стол из своей руки девятку любой масти; выложить на стол шестёрку, семёрку или восьмёрку любой масти, если на столе уже лежит карта той же масти достоинством на единицу выше; выложить на стол десятку, валета, даму, короля или туза любой масти, если на столе уже лежит карта той же масти достоинством на единицу ниже. Например, девятку пик можно выложить на стол в любой момент, для выкладывания семёрки треф необходимо наличие на столе восьмёрки треф, а для выкладывания туза червей необходимо наличие на столе короля червей. Если игрок не может выложить на стол ни одну карту из своей руки, то ход переходит к сопернику. Обратите внимание: нельзя пропустить ход просто такxa0— всегда необходимо выложить карту на стол корректным образом, если это возможно. Помимо того, что каждый игрок стремится избавиться от карт в своей руке, Алиса и Боб также хотят, чтобы в конце игры в руке у их соперника карт осталось как можно больше, а в их рукеxa0— как можно меньше. Напомним, что игра заканчивается, как только один из игроков выкладывает на стол последнюю карту из своей руки. Результатом игры назовём совокупность из информации о том, кто из двух игроков выиграет при оптимальной игре, а также о том, сколько карт останется в руке у проигравшего. Пусть Алиса и Боб уже взяли в руки свои $$$18$$$ карт каждый, но ещё не решили, кто из них будет ходить первым. Величиной важности первого хода для данного расклада назовём абсолютную разность между результатами игры в случае, если первой будет ходить Алиса, и в случае, если первым будет ходить Боб. Например, если в обоих случаях выиграет Боб, но в одном случае у Алисы останется $$$6$$$ карт в руке в конце игры, а во второмxa0— всего $$$2$$$, то величина важности первого хода равна $$$4$$$. Если же в одном случае выиграет Алиса и у Боба останется $$$5$$$ карт в руке, а во втором случае выиграет Боб и у Алисы останется $$$3$$$ карты в руке, то величина важности первого хода равна $$$8$$$. Ребята хотят узнать, насколько разной бывает величина важности первого хода для разных раскладов. По заданному числу $$$k le 26$$$ помогите им найти такие $$$k$$$ раскладов, что величины важности первого хода для всех нихxa0— различные целые числа. Выходные данные Выведите $$$k$$$ пар строк. Каждая пара строк должна соответствовать некоторому раскладу. Величины важности первого хода для всех выведенных раскладов должны быть различными целыми числами. В первой строке каждой пары выведите $$$18$$$ строк длины $$$2$$$ через пробел, описывающих карты Алисы в любом порядке. Первый символ строки должен обозначать достоинство картыxa0— символ из набора 6, 7, 8, 9, T, J, Q, K, A, обозначающий шестёрку, семёрку, восьмёрку, девятку, десятку, валета, даму, короля и туза соответственно. Второй символ строки должен обозначать масть картыxa0— символ из набора C, D, S, H, обозначающий трефы, бубны, пики и черви соответственно. Во второй строке выведите $$$18$$$ строк длины $$$2$$$ через пробел, описывающих карты Боба в том же формате. Каждая из $$$36$$$ возможных карт должна находиться в руке одного из двух игроков в единственном экземпляре. Примечание В первом выведенном раскладе все девятки находятся в руке у Алисы. Даже если Боб будет ходить первым, ему всё равно придётся пропустить первый же свой ход. Следовательно, первый ход при таком раскладе имеет важность $$$0$$$. Во втором выведенном раскладе вне зависимости от того, чьим будет первый ход, выиграет Алиса. Однако если Алиса будет ходить первой, то у Боба в конце игры в руке останется одна карта, а если же она будет ходить второй, то у Боба останется пять карт. Соответственно, величина важности первого хода при таком раскладе равна $$$4$$$. | 2,300 | brute force | false | false | false | false | false | false | true | false | false | false |
1098B | Problem - 1098B - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags brute force constructive algorithms greedy math *2100 No tag edit access → Contest materials , that differs from the given table in the minimum number of characters. Input First line contains two positive integers $$$n$$$ and $$$m$$$xa0— number of rows and columns in the table you are given ($$$2 leq n, m, n imes m leq 300,000$$$). Then, $$$n$$$ lines describing the table follow. Each line contains exactly $$$m$$$ characters «A», «G», «C», «T». Output Output $$$n$$$ lines, $$$m$$$ characters each. This table must be nice and differ from the input table in the minimum number of characters. Examples Input 2 2 AG CT Output AG CT Input 3 5 AGCAG AGCAG AGCAG Output TGCAT CATGC TGCAT Note In the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 07:56:50 (l3). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 2,100 | math | true | false | false | false | false | false | false | false | false | false |
1906A | You are playing a word puzzle. The puzzle starts with a $$$3$$$ by $$$3$$$ grid, where each cell contains either the letter A, B, or C. The goal of this puzzle is to find the lexicographically smallest possible word of length $$$3$$$. The word can be formed by choosing three different cells where the cell containing the first letter is adjacent to the cell containing the second letter, and the cell containing the second letter is adjacent to the cell containing the third letter. Two cells are adjacent to each other if they share a border or a corner, as shown in the following illustration. Formally, if $$$(r, c)$$$ denotes the cell in the $$$r$$$-th row and $$$c$$$-th column, then cell $$$(r, c)$$$ is adjacent to cell $$$(r, c + 1)$$$, $$$(r - 1, c + 1)$$$, $$$(r - 1, c)$$$, $$$(r - 1, c - 1)$$$, $$$(r, c - 1)$$$, $$$(r + 1, c - 1)$$$, $$$(r + 1, c)$$$, and $$$(r + 1, c + 1)$$$. Determine the lexicographically smallest possible word of length $$$3$$$ that you can find within the grid. A string $$$s$$$ of length $$$n$$$ is lexicographically smaller than string $$$t$$$ of the same length if there exists an integer $$$1 leq i leq n$$$ such that $$$s_j = t_j$$$ for all $$$1 leq j < i$$$, and $$$s_i < t_i$$$ in alphabetical order. The following illustration shows some examples on some grids and their the lexicographically smallest possible word of length $$$3$$$ that you can find within the grids. Input Input consists of three lines, each containing three letters, representing the puzzle grid. Each letter in the grid can only be either A, B, or C. | 1,000 | brute force | false | false | false | false | false | false | true | false | false | false |
1475C | At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, $$$a$$$ boys and $$$b$$$ girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know $$$k$$$ possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if $$$a=3$$$, $$$b=4$$$, $$$k=4$$$ and the couples $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(3, 4)$$$ are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): $$$(1, 3)$$$ and $$$(2, 2)$$$; $$$(3, 4)$$$ and $$$(1, 3)$$$; But the following combinations are not possible: $$$(1, 3)$$$ and $$$(1, 2)$$$xa0— the first boy enters two pairs; $$$(1, 2)$$$ and $$$(2, 2)$$$xa0— the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer $$$t$$$ ($$$1 le t le 10^4$$$)xa0— the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$k$$$ ($$$1 le a, b, k le 2 cdot 10^5$$$)xa0— the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains $$$k$$$ integers $$$a_1, a_2, ldots a_k$$$. ($$$1 le a_i le a$$$), where $$$a_i$$$ is the number of the boy in the pair with the number $$$i$$$. The third line of each test case contains $$$k$$$ integers $$$b_1, b_2, ldots b_k$$$. ($$$1 le b_i le b$$$), where $$$b_i$$$ is the number of the girl in the pair with the number $$$i$$$. It is guaranteed that the sums of $$$a$$$, $$$b$$$, and $$$k$$$ over all test cases do not exceed $$$2 cdot 10^5$$$. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integerxa0— the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Note In the first test case, the following combinations of pairs fit: $$$(1, 2)$$$ and $$$(3, 4)$$$; $$$(1, 3)$$$ and $$$(2, 2)$$$; $$$(1, 3)$$$ and $$$(3, 4)$$$; $$$(2, 2)$$$ and $$$(3, 4)$$$. There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: $$$(1, 1)$$$ and $$$(2, 2)$$$; $$$(1, 2)$$$ and $$$(2, 1)$$$. | 1,400 | math | true | false | false | false | false | false | false | false | false | false |
1333B | Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers $$$a$$$ and $$$b$$$ of length $$$n$$$. It turned out that array $$$a$$$ contains only elements from the set $$${-1, 0, 1}$$$. Anton can perform the following sequence of operations any number of times: 1. Choose any pair of indexes $$$(i, j)$$$ such that $$$1 le i < j le n$$$. It is possible to choose the same pair $$$(i, j)$$$ more than once. 2. Add $$$a_i$$$ to $$$a_j$$$. In other words, $$$j$$$-th element of the array becomes equal to $$$a_i + a_j$$$. For example, if you are given array $$$[1, -1, 0]$$$, you can transform it only to $$$[1, -1, -1]$$$, $$$[1, 0, 0]$$$ and $$$[1, -1, 1]$$$ by one operation. Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $$$a$$$ so that it becomes equal to array $$$b$$$. Can you help him? Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 10000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 le n le 10^5$$$) xa0— the length of arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$-1 le a_i le 1$$$) xa0— elements of array $$$a$$$. There can be duplicates among elements. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, dots, b_n$$$ ($$$-10^9 le b_i le 10^9$$$) xa0— elements of array $$$b$$$. There can be duplicates among elements. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. Output For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing the described operations, or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 5 3 1 -1 0 1 1 -2 3 0 1 1 0 2 2 2 1 0 1 41 2 -1 0 -1 -41 5 0 1 -1 1 -1 1 1 -1 1 -1 Note In the first test-case we can choose $$$(i, j)=(2, 3)$$$ twice and after that choose $$$(i, j)=(1, 2)$$$ twice too. These operations will transform $$$[1, -1, 0] o [1, -1, -2] o [1, 1, -2]$$$ In the second test case we can't make equal numbers on the second position. In the third test case we can choose $$$(i, j)=(1, 2)$$$ $$$41$$$ times. The same about the fourth test case. In the last lest case, it is impossible to make array $$$a$$$ equal to the array $$$b$$$. | 1,100 | greedy | false | true | false | false | false | false | false | false | false | false |
1787D | There are $$$n$$$ points $$$1,2,ldots,n$$$, each point $$$i$$$ has a number $$$a_i$$$ on it. You're playing a game on them. Initially, you are at point $$$1$$$. When you are at point $$$i$$$, take following steps: If $$$1le ile n$$$, go to $$$i+a_i$$$, Otherwise, the game ends. Before the game begins, you can choose two integers $$$x$$$ and $$$y$$$ satisfying $$$1le xle n$$$, $$$-n le y le n$$$ and replace $$$a_x$$$ with $$$y$$$ (set $$$a_x := y$$$). Find the number of distinct pairs $$$(x,y)$$$ such that the game that you start after making the change ends in a finite number of steps. Notice that you do not have to satisfy $$$a_x ot=y$$$. Input Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1le tle 10^4)$$$ — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1le nle 2cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ integers $$$a_1,a_2,ldots,a_n$$$ ($$$-n le a_i le n$$$) — the numbers on the axis. It's guaranteed that the sum of $$$n$$$ does not exceed $$$2cdot 10^5$$$. Note In the first test case, the pairs $$$(x,y)$$$ with which the game ends are $$$(1,-1)$$$ and $$$(1,1)$$$, corresponding to the routes $$$1 ightarrow 0$$$ and $$$1 ightarrow 2$$$. Note that $$$(1,2)$$$ is invalid since when $$$n=1$$$, $$$y=2$$$ violates $$$-nle yle n$$$. $$$(1,0)$$$ is also invalid since you will go from $$$1$$$ to $$$1$$$ forever. In the second test case, the pairs are $$$(1,-2),(1,-1),(1,2),(2,-2),(2,-1),(2,0),(2,1),(2,2)$$$. In the fourth test case, the pairs are $$$(1,-2),(1,-1),(1,1),(1,2),(2,-2),(2,1),(2,2)$$$. | 1,900 | implementation | false | false | true | false | false | false | false | false | false | false |
835B | Problem - 835B - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags greedy *1100 No tag edit access → Contest materials . Announcement") . The second line contains integer _n_ (1u2009≤u2009_n_u2009<u200910100000). There are no leading zeros in _n_. It's guaranteed that this situation is possible. Output Print the minimum number of digits in which the initial number and _n_ can differ. Examples Input 3 11 Output 1 Input 3 99 Output 0 Note In the first example, the initial number could be 12. In the second example the sum of the digits of _n_ is not less than _k_. The initial number could be equal to _n_. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 09:39:25 (l3). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,100 | greedy | false | true | false | false | false | false | false | false | false | false |
1270H | Suppose that we have an array of $$$n$$$ distinct numbers $$$a_1, a_2, dots, a_n$$$. Let's build a graph on $$$n$$$ vertices as follows: for every pair of vertices $$$i < j$$$ let's connect $$$i$$$ and $$$j$$$ with an edge, if $$$a_i < a_j$$$. Let's define weight of the array to be the number of connected components in this graph. For example, weight of array $$$[1, 4, 2]$$$ is $$$1$$$, weight of array $$$[5, 4, 3]$$$ is $$$3$$$. You have to perform $$$q$$$ queries of the following formxa0— change the value at some position of the array. After each operation, output the weight of the array. Updates are not independent (the change stays for the future). Input The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 le n, q le 5 cdot 10^5$$$)xa0— the size of the array and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$1 le a_i le 10^6$$$)xa0— the initial array. Each of the next $$$q$$$ lines contains two integers $$$pos$$$ and $$$x$$$ ($$$1 le pos le n$$$, $$$1 le x le 10^6, x e a_{pos}$$$). It means that you have to make $$$a_{pos}=x$$$. It's guaranteed that at every moment of time, all elements of the array are different. Output After each query, output the weight of the array. Example Input 5 3 50 40 30 20 10 1 25 3 45 1 48 Note After the first query array looks like $$$[25, 40, 30, 20, 10]$$$, the weight is equal to $$$3$$$. After the second query array looks like $$$[25, 40, 45, 20, 10]$$$, the weight is still equal to $$$3$$$. After the third query array looks like $$$[48, 40, 45, 20, 10]$$$, the weight is equal to $$$4$$$. | 3,300 | data structures | false | false | false | false | true | false | false | false | false | false |
632B | Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are _n_ pieces, and the _i_-th piece has a strength _p__i_. The way to split up game pieces is split into several steps: 1. First, Alice will split the pieces into two different groups _A_ and _B_. This can be seen as writing the assignment of teams of a piece in an _n_ character string, where each character is _A_ or _B_. 2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change _A_ to _B_ and _B_ to _A_). He can do this step at most once. 3. Alice will get all the pieces marked _A_ and Bob will get all the pieces marked _B_. The strength of a player is then the sum of strengths of the pieces in the group. Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve. Input The first line contains integer _n_ (1u2009≤u2009_n_u2009≤u20095·105) — the number of game pieces. The second line contains _n_ integers _p__i_ (1u2009≤u2009_p__i_u2009≤u2009109) — the strength of the _i_-th piece. The third line contains _n_ characters _A_ or _B_ — the assignment of teams after the first step (after Alice's step). Output Print the only integer _a_ — the maximum strength Bob can achieve. Note In the first sample Bob should flip the suffix of length one. In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5. In the third sample Bob should do nothing. | 1,400 | constructive algorithms | false | false | false | false | false | true | false | false | false | false |
955B | Problem - 955B - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags implementation *1400 No tag edit access → Contest materials ") . For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of _a_-s and others — a group of _b_-s), but cccc is not since in each possible consequent partition letters in these two groups coincide. You're given a string _s_. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string. Input The only line contains _s_ (1u2009≤u2009_s_u2009≤u2009105) consisting of lowercase latin letters. Output Print «Yes» if the string can be split according to the criteria above or «No» otherwise. Each letter can be printed in arbitrary case. Examples Input ababa Output Yes Input zzcxx Output Yes Input yeee Output No Note In sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable. There's no suitable partition in sample case three. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 08:59:08 (k1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,400 | implementation | false | false | true | false | false | false | false | false | false | false |
839B | Daenerys Targaryen has an army consisting of _k_ groups of soldiers, the _i_-th group contains _a__i_ soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has _n_ rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1,u20092}, {3,u20094}, {4,u20095}, {5,u20096} or {7,u20098}. A row in the airplane Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats. Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied. Input The first line contains two integers _n_ and _k_ (1u2009≤u2009_n_u2009≤u200910000, 1u2009≤u2009_k_u2009≤u2009100)xa0— the number of rows and the number of groups of soldiers, respectively. The second line contains _k_ integers _a_1,u2009_a_2,u2009_a_3,u2009...,u2009_a__k_ (1u2009≤u2009_a__i_u2009≤u200910000), where _a__i_ denotes the number of soldiers in the _i_-th group. It is guaranteed that _a_1u2009+u2009_a_2u2009+u2009...u2009+u2009_a__k_u2009≤u20098·_n_. Output If we can place the soldiers in the airplane print "YES" (without quotes). Otherwise print "NO" (without quotes). You can choose the case (lower or upper) for each letter arbitrary. Note In the first sample, Daenerys can place the soldiers like in the figure below: In the second sample, there is no way to place the soldiers in the plane since the second group soldier will always have a seat neighboring to someone from the first group. In the third example Daenerys can place the first group on seats (1,u20092,u20097,u20098), and the second group an all the remaining seats. In the fourth example she can place the first two groups on seats (1,u20092) and (7,u20098), the third group on seats (3), and the fourth group on seats (5,u20096). | 1,900 | greedy | false | true | false | false | false | false | false | false | false | false |
1521B | Nastia has received an array of $$$n$$$ positive integers as a gift. She calls such an array $$$a$$$ good that for all $$$i$$$ ($$$2 le i le n$$$) takes place $$$gcd(a_{i - 1}, a_{i}) = 1$$$, where $$$gcd(u, v)$$$ denotes the and two integers $$$x, y$$$ ($$$1 le x, y le 2 cdot 10^9$$$) so that $$$min{(a_i, a_j)} = min{(x, y)}$$$. Then change $$$a_i$$$ to $$$x$$$ and $$$a_j$$$ to $$$y$$$. The girl asks you to make the array good using at most $$$n$$$ operations. It can be proven that this is always possible. Input The first line contains a single integer $$$t$$$ ($$$1 le t le 10,000$$$)xa0— the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 le n le 10^5$$$)xa0— the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_{n}$$$ ($$$1 le a_i le 10^9$$$)xa0— the array which Nastia has received as a gift. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$2 cdot 10^5$$$. Output For each of $$$t$$$ test cases print a single integer $$$k$$$ ($$$0 le k le n$$$)xa0— the number of operations. You don't need to minimize this number. In each of the next $$$k$$$ lines print $$$4$$$ integers $$$i$$$, $$$j$$$, $$$x$$$, $$$y$$$ ($$$1 le i eq j le n$$$, $$$1 le x, y le 2 cdot 10^9$$$) so that $$$min{(a_i, a_j)} = min{(x, y)}$$$xa0— in this manner you replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. If there are multiple answers, print any. Example Input 2 5 9 6 3 11 15 3 7 5 13 Output 2 1 5 11 9 2 5 7 6 0 Note Consider the first test case. Initially $$$a = [9, 6, 3, 11, 15]$$$. In the first operation replace $$$a_1$$$ with $$$11$$$ and $$$a_5$$$ with $$$9$$$. It's valid, because $$$min{(a_1, a_5)} = min{(11, 9)} = 9$$$. After this $$$a = [11, 6, 3, 11, 9]$$$. In the second operation replace $$$a_2$$$ with $$$7$$$ and $$$a_5$$$ with $$$6$$$. It's valid, because $$$min{(a_2, a_5)} = min{(7, 6)} = 6$$$. After this $$$a = [11, 7, 3, 11, 6]$$$xa0— a good array. In the second test case, the initial array is already good. | 1,300 | math | true | false | false | false | false | false | false | false | false | false |
2022D1 | Enter Register HOME TOP CATALOG CONTESTS GYM PROBLEMSET GROUPS RATING EDU API CALENDAR HELP RAYAN Codeforces Round 978 (Div. 2) Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags binary search brute force constructive algorithms implementation interactive *1900 No tag edit access → Contest materials Announcement (en) Tutorial (en) PROBLEMS SUBMIT STATUS STANDINGS CUSTOM TEST D1. Asesino (Easy Version) time limit per test2.5 seconds memory limit per test256 megabytes This is the easy version of the problem. In this version, you can ask at most $$$n+69$$$ questions. You can make hacks only if both versions of the problem are solved. This is an interactive problem. It is a tradition in Mexico's national IOI trainings to play the game "Asesino", which is similar to "Among Us" or "Mafia". Today, $$$n$$$ players, numbered from $$$1$$$ to $$$n$$$, will play "Asesino" with the following three roles: Knight: a Knight is someone who always tells the truth. Knave: a Knave is someone who always lies. Impostor: an Impostor is someone everybody thinks is a Knight, but is secretly a Knave. Each player will be assigned a role in the game. There will be exactly one Impostor but there can be any (possible zero) number of Knights and Knaves. As the game moderator, you have accidentally forgotten the roles of everyone, but you need to determine the player who is the Impostor. To determine the Impostor, you will ask some questions. In each question, you will pick two players $$$i$$$ and $$$j$$$ ($$$1 leq i, j leq n$$$; $$$i eq j$$$) and ask if player $$$i$$$ thinks that player $$$j$$$ is a Knight. The results of the question is shown in the table below. Knight Knave Impostor Knight Yes No Yes Knave No Yes No Impostor No Yes — The response of the cell in row $$$a$$$ and column $$$b$$$ is the result of asking a question when $$$i$$$ has role $$$a$$$ and $$$j$$$ has row $$$b$$$. For example, the "Yes" in the top right cell belongs to row "Knight" and column "Impostor", so it is the response when $$$i$$$ is a Knight and $$$j$$$ is an Impostor. Find the Impostor in at most $$$n + 69$$$ questions. Note: the grader is adaptive: the roles of the players are not fixed in the beginning and may change depending on your questions. However, it is guaranteed that there exists an assignment of roles that is consistent with all previously asked questions under the constraints of this problem. Input The first line of input contains a single integer $$$t$$$ ($$$1 leq t leq 10^3$$$)xa0— the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 le n le 10^5$$$)xa0— the number of people playing the game. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. Interaction To ask a question, output a line in the following format: "? i j" ($$$1 leq i,j leq n$$$; $$$i eq j$$$)xa0— to ask player $$$i$$$ if they think player $$$j$$$ is a Knight. The jury will output a "1" if player $$$i$$$ thinks player $$$j$$$ is a Knight, and "0" otherwise. When you have determined which player the Impostor is, output a line in the following format: "! i" ($$$1 leq i leq n$$$)xa0— the Impostor is player $$$i$$$. Note that answering does not count to your limit of $$$n+69$$$ questions. If you have made an invalid output, used more than $$$n+69$$$ questions or wrongly determined the Impostor, the jury will respond with "-1" and you will receive a Wrong Answer verdict. Upon receiving "-1", your program must terminate immediately. Otherwise, you may receive an arbitrary verdict because your solution might be reading from a closed stream. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; sys.stdout.flush() in Python; std::io::stdout().flush() in Rust; see the documentation for other languages. Hack format For hacks, use the following format. The first line should contain a single integer $$$t$$$xa0— the number of test cases. The first line of each test case should contain the integer $$$n$$$ followed by the string "manual". The second line contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$-1 le a_i le 1$$$)xa0— the roles of each player. $$$1$$$ denotes a Knight, $$$0$$$ denotes a Knave, and $$$-1$$$ dentoes an Impostor. There must be exactly one Impostor, that is there must be exactly one index $$$i$$$ such that $$$a_i=-1$$$. As an example, the hack format for the example input is: 2 7 manual 0 1 0 -1 0 1 0 4 manual 0 1 -1 0 Example input 2 7 1 0 0 1 1 0 0 1 4 0 1 1 1 output ? 1 3 ? 7 6 ? 2 5 ? 6 2 ? 4 5 ? 4 6 ? 1 4 ? 2 4 ! 4 ? 1 2 ? 2 3 ? 3 4 ? 4 1 ! 3 Note Note that the example test cases do not represent an optimal strategy for asking questions and are only shown for the sake of demonstrating the interaction format. Specifically, we cannot determine which player is the Impostor from the questions asked in the examples. In the first test case of the example, players at indices $$$2$$$ and $$$6$$$ are Knights, players at indices $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ are Knaves, and the Impostor is at index $$$4$$$. The following is an explanation of the questions asked: In the first query, player $$$i$$$ is a Knave and player $$$j$$$ is a Knave. The answer is "yes" since Knaves always lie. In the second query, player $$$i$$$ is a Knave and player $$$j$$$ is a Knight. The answer is "no" since Knaves always lie. In the third query, player $$$i$$$ is a Knight and player $$$j$$$ is a Knave. The answer is "no" since Knights always tell the truth. In the fourth query, player $$$i$$$ is a Knight and player $$$j$$$ is a Knight. The answer is "yes" since Knights always tell the truth. In the fifth query, player $$$i$$$ is a Impostor and player $$$j$$$ is a Knave. The answer is "yes" since the Impostor always lies. In the sixth query, player $$$i$$$ is a Impostor and player $$$j$$$ is a Knight. The answer is "no" since the Impostor always lies. In the seventh query, player $$$i$$$ is a Knave and player $$$j$$$ is a Impostor. The answer is "no" since Knaves always lie and Knaves thinks that the Impostor is a Knight. In the eighth query, player $$$i$$$ is a Knight and player $$$j$$$ is a Impostor. The answer is "yes" since Knights always tell the truth and Knights think that the Impostor is a Knight. Codeforces (c) Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/29/2024 23:37:58 (i1). Desktop version, switch to mobile version. Privacy Policy Supported by | 1,900 | implementation | false | false | true | false | false | false | false | false | false | false |
173C | Let's consider a _k_u2009×u2009_k_ square, divided into unit squares. Please note that _k_u2009≥u20093 and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one of two cases: either we've reached the square's border or the square following after the next square is already painted. We finish painting at the moment when we cannot move in any direction and paint a square. The figure that consists of the painted squares is a spiral. The figure shows examples of spirals for _k_u2009=u20093,u20095,u20097,u20099. You have an _n_u2009×u2009_m_ table, each of its cells contains a number. Let's consider all possible spirals, formed by the table cells. It means that we consider all spirals of any size that don't go beyond the borders of the table. Let's find the sum of the numbers of the cells that form the spiral. You have to find the maximum of those values among all spirals. Input The first line contains two integers _n_ and _m_ (3u2009≤u2009_n_,u2009_m_u2009≤u2009500) — the sizes of the table. Each of the next _n_ lines contains _m_ space-separated integers: the _j_-th number in the _i_-th line _a__ij_ (u2009-u20091000u2009≤u2009_a__ij_u2009≤u20091000) is the number recorded in the _j_-th cell of the _i_-th row of the table. Output Print a single number — the maximum sum of numbers among all spirals. Examples Input 6 5 0 0 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 Input 6 6 -3 2 0 1 5 -1 4 -1 2 -3 0 1 -5 1 2 4 1 -2 0 -2 1 3 -1 2 3 1 4 -3 -2 0 -1 2 -1 3 1 2 Note In the first sample the spiral with maximum sum will cover all 1's of the table. In the second sample the spiral may cover only six 1's. | 1,900 | dp | false | false | false | true | false | false | false | false | false | false |
1765E | Monocarp is playing a MMORPG. There are two commonly used types of currency in this MMORPG — gold coins and silver coins. Monocarp wants to buy a new weapon for his character, and that weapon costs $$$n$$$ silver coins. Unfortunately, right now, Monocarp has no coins at all. Monocarp can earn gold coins by completing quests in the game. Each quest yields exactly one gold coin. Monocarp can also exchange coins via the in-game trading system. Monocarp has spent days analyzing the in-game economy; he came to the following conclusion: it is possible to sell one gold coin for $$$a$$$ silver coins (i.u2009e. Monocarp can lose one gold coin to gain $$$a$$$ silver coins), or buy one gold coin for $$$b$$$ silver coins (i.u2009e. Monocarp can lose $$$b$$$ silver coins to gain one gold coin). Now Monocarp wants to calculate the minimum number of quests that he has to complete in order to have at least $$$n$$$ silver coins after some abuse of the in-game economy. Note that Monocarp can perform exchanges of both types (selling and buying gold coins for silver coins) any number of times. Input The first line contains one integer $$$t$$$ ($$$1 le t le 10^4$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 le n le 10^7$$$; $$$1 le a, b le 50$$$). Output For each test case, print one integer — the minimum possible number of quests Monocarp has to complete. Example Input 4 100 25 30 9999997 25 50 52 50 48 49 50 1 Note In the first test case of the example, Monocarp should complete $$$4$$$ quests, and then sell $$$4$$$ gold coins for $$$100$$$ silver coins. In the second test case, Monocarp should complete $$$400000$$$ quests, and then sell $$$400000$$$ gold coins for $$$10$$$ million silver coins. In the third test case, Monocarp should complete $$$1$$$ quest, sell the gold coin for $$$50$$$ silver coins, buy a gold coin for $$$48$$$ silver coins, and then sell it again for $$$50$$$ coins. So, he will have $$$52$$$ silver coins. In the fourth test case, Monocarp should complete $$$1$$$ quest and then sell the gold coin he has obtained for $$$50$$$ silver coins. | 1,000 | math | true | false | false | false | false | false | false | false | false | false |
732F | Berland is a tourist country! At least, it can become suchxa0— the government of Berland is confident about this. There are _n_ cities in Berland, some pairs of which are connected by two-ways roads. Each road connects two different cities. In Berland there are no roads which connect the same pair of cities. It is possible to get from any city to any other city using given two-ways roads. According to the reform each road will become one-way. It will be oriented to one of two directions. To maximize the tourist attraction of Berland, after the reform for each city _i_ the value _r__i_ will be calculated. It will equal to the number of cities _x_ for which there is an oriented path from the city _i_ to the city _x_. In other words, _r__i_ will equal the number of cities which can be reached from the city _i_ by roads. The government is sure that tourist's attention will be focused on the minimum value of _r__i_. Help the government of Berland make the reform to maximize the minimum of _r__i_. Input The first line contains two integers _n_,u2009_m_ (2u2009≤u2009_n_u2009≤u2009400u2009000,u20091u2009≤u2009_m_u2009≤u2009400u2009000)xa0— the number of cities and the number of roads. The next _m_ lines describe roads in Berland: the _j_-th of them contains two integers _u__j_ and _v__j_ (1u2009≤u2009_u__j_,u2009_v__j_u2009≤u2009_n_, _u__j_u2009≠u2009_v__j_), where _u__j_ and _v__j_ are the numbers of cities which are connected by the _j_-th road. The cities are numbered from 1 to _n_. It is guaranteed that it is possible to get from any city to any other by following two-ways roads. In Berland there are no roads which connect the same pair of cities. Output In the first line print single integerxa0— the maximum possible value _min_1u2009≤u2009_i_u2009≤u2009_n_{_r__i_} after the orientation of roads. The next _m_ lines must contain the description of roads after the orientation: the _j_-th of them must contain two integers _u__j_,u2009_v__j_, it means that the _j_-th road will be directed from the city _u__j_ to the city _v__j_. Print roads in the same order as they are given in the input data. Example Input 7 9 4 3 2 6 7 1 4 1 7 3 3 5 7 4 6 5 2 5 Output 4 4 3 6 2 7 1 1 4 3 7 5 3 7 4 5 6 2 5 | 2,300 | graphs | false | false | false | false | false | false | false | false | false | true |
1442D | Problem - 1442D - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags data structures divide and conquer dp greedy *2800 No tag edit access → Contest materials : the number of arrays and operations. Each of the next $$$n$$$ lines contain an array. The first integer in each line is $$$t_i$$$ ($$$1 le t_i le 10^6$$$): the size of the $$$i$$$-th array. The following $$$t_i$$$ integers $$$a_{i, j}$$$ ($$$0 le a_{i, 1} le ldots le a_{i, t_i} le 10^8$$$) are the elements of the $$$i$$$-th array. It is guaranteed that $$$k le sumlimits_{i=1}^n t_i le 10^6$$$. Output Print one integer: the maximum possible sum of all elements in Vasya's pocket after $$$k$$$ operations. Example Input 3 3 2 5 10 3 1 2 3 2 1 20 Output 26 Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 03:46:27 (f1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 2,800 | greedy | false | true | false | false | false | false | false | false | false | false |
919A | We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $$$a$$$ yuan for $$$b$$$ kilos (You don't need to care about what "yuan" is), the same as $$$a/b$$$ yuan for a kilo. Now imagine you'd like to buy $$$m$$$ kilos of apples. You've asked $$$n$$$ supermarkets and got the prices. Find the minimum cost for those apples. You can assume that there are enough apples in all supermarkets. Input The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 leq n leq 5,000$$$, $$$1 leq m leq 100$$$), denoting that there are $$$n$$$ supermarkets and you want to buy $$$m$$$ kilos of apples. The following $$$n$$$ lines describe the information of the supermarkets. Each line contains two positive integers $$$a, b$$$ ($$$1 leq a, b leq 100$$$), denoting that in this supermarket, you are supposed to pay $$$a$$$ yuan for $$$b$$$ kilos of apples. Output The only line, denoting the minimum cost for $$$m$$$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $$$10^{-6}$$$. Formally, let your answer be $$$x$$$, and the jury's answer be $$$y$$$. Your answer is considered correct if $$$frac{x - y}{max{(1, y)}} le 10^{-6}$$$. Note In the first sample, you are supposed to buy $$$5$$$ kilos of apples in supermarket $$$3$$$. The cost is $$$5/3$$$ yuan. In the second sample, you are supposed to buy $$$1$$$ kilo of apples in supermarket $$$2$$$. The cost is $$$98/99$$$ yuan. | 800 | greedy | false | true | false | false | false | false | false | false | false | false |
1660E | You are given a binary matrix $$$A$$$ of size $$$n imes n$$$. Rows are numbered from top to bottom from $$$1$$$ to $$$n$$$, columns are numbered from left to right from $$$1$$$ to $$$n$$$. The element located at the intersection of row $$$i$$$ and column $$$j$$$ is called $$$A_{ij}$$$. Consider a set of $$$4$$$ operations: 1. Cyclically shift all rows up. The row with index $$$i$$$ will be written in place of the row $$$i-1$$$ ($$$2 le i le n$$$), the row with index $$$1$$$ will be written in place of the row $$$n$$$. 2. Cyclically shift all rows down. The row with index $$$i$$$ will be written in place of the row $$$i+1$$$ ($$$1 le i le n - 1$$$), the row with index $$$n$$$ will be written in place of the row $$$1$$$. 3. Cyclically shift all columns to the left. The column with index $$$j$$$ will be written in place of the column $$$j-1$$$ ($$$2 le j le n$$$), the column with index $$$1$$$ will be written in place of the column $$$n$$$. 4. Cyclically shift all columns to the right. The column with index $$$j$$$ will be written in place of the column $$$j+1$$$ ($$$1 le j le n - 1$$$), the column with index $$$n$$$ will be written in place of the column $$$1$$$. The $$$3 imes 3$$$ matrix is shown on the left before the $$$3$$$-rd operation is applied to it, on the rightxa0— after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order. After that, you can perform an arbitrary (possibly zero) number of new xor-operations: Select any element $$$A_{ij}$$$ and assign it with new value $$$A_{ij} oplus 1$$$. In other words, the value of $$$(A_{ij} + 1) bmod 2$$$ will have to be written into element $$$A_{ij}$$$. Each application of this xor-operation costs one burl. Note that the $$$4$$$ shift operationsxa0— are free. These $$$4$$$ operations can only be performed before xor-operations are performed. Output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, $$$A_{ij} = 1$$$ if $$$i = j$$$ and $$$A_{ij} = 0$$$ otherwise). Input The first line of the input contains an integer $$$t$$$ ($$$1 le t le 10^4$$$)xa0—the number of test cases in the test. The descriptions of the test cases follow. Before each test case, an empty line is written in the input. The first line of each test case contains a single number $$$n$$$ ($$$1 le n le 2000$$$) This is followed by $$$n$$$ lines, each containing exactly $$$n$$$ characters and consisting only of zeros and ones. These lines describe the values in the elements of the matrix. It is guaranteed that the sum of $$$n^2$$$ values over all test cases does not exceed $$$4 cdot 10^6$$$. Output For each test case, output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. In other words, print the minimum number of xor-operations it will take after applying cyclic shifts to the matrix for the $$$A$$$ matrix to become unitary. Example Input 4 3 010 011 100 5 00010 00001 10000 01000 00100 2 10 10 4 1111 1011 1111 1111 Note In the first test case, you can do the following: first, shift all the rows down cyclically, then the main diagonal of the matrix will contain only "1". Then it will be necessary to apply xor-operation to the only "1" that is not on the main diagonal. In the second test case, you can make a unitary matrix by applying the operation $$$2$$$xa0— cyclic shift of rows upward twice to the matrix. | 1,600 | greedy | false | true | false | false | false | false | false | false | false | false |
1090D | Vasya had an array of $$$n$$$ integers, each element of the array was from $$$1$$$ to $$$n$$$. He chose $$$m$$$ pairs of different positions and wrote them down to a sheet of paper. Then Vasya compared the elements at these positions, and wrote down the results of the comparisons to another sheet of paper. For each pair he wrote either "greater", "less", or "equal". After several years, he has found the first sheet of paper, but he couldn't find the second one. Also he doesn't remember the array he had. In particular, he doesn't remember if the array had equal elements. He has told this sad story to his informatics teacher Dr Helen. She told him that it could be the case that even if Vasya finds his second sheet, he would still not be able to find out whether the array had two equal elements. Now Vasya wants to find two arrays of integers, each of length $$$n$$$. All elements of the first array must be distinct, and there must be two equal elements in the second array. For each pair of positions Vasya wrote at the first sheet of paper, the result of the comparison must be the same for the corresponding elements of the first array, and the corresponding elements of the second array. Help Vasya find two such arrays of length $$$n$$$, or find out that there are no such arrays for his sets of pairs. Input The first line of input contains two integers $$$n$$$, $$$m$$$xa0— the number of elements in the array and number of comparisons made by Vasya ($$$1 le n le 100,000$$$, $$$0 le m le 100,000$$$). Each of the following $$$m$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ xa0— the positions of the $$$i$$$-th comparison ($$$1 le a_i, b_i le n$$$; $$$a_i e b_i$$$). It's guaranteed that any unordered pair is given in the input at most once. Output The first line of output must contain "YES" if there exist two arrays, such that the results of comparisons would be the same, and all numbers in the first one are distinct, and the second one contains two equal numbers. Otherwise it must contain "NO". If the arrays exist, the second line must contain the array of distinct integers, the third line must contain the array, that contains at least one pair of equal elements. Elements of the arrays must be integers from $$$1$$$ to $$$n$$$. | 1,800 | constructive algorithms | false | false | false | false | false | true | false | false | false | false |
167C | In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — _a_ and _b_. The order of the numbers is not important. Let's consider _a_u2009≤u2009_b_ for the sake of definiteness. The players can cast one of the two spells in turns: Replace _b_ with _b_u2009-u2009_a__k_. Number _k_ can be chosen by the player, considering the limitations that _k_u2009>u20090 and _b_u2009-u2009_a__k_u2009≥u20090. Number _k_ is chosen independently each time an active player casts a spell. Replace _b_ with _b_xa0_mod_xa0_a_. If _a_u2009>u2009_b_, similar moves are possible. If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses. To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second. Input The first line contains a single integer _t_ — the number of input data sets (1u2009≤u2009_t_u2009≤u2009104). Each of the next _t_ lines contains two integers _a_, _b_ (0u2009≤u2009_a_,u2009_b_u2009≤u20091018). The numbers are separated by a space. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Output For any of the _t_ input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input. Examples Output First Second Second First Note In the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win. In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win. In the third sample, the first player has no moves. In the fourth sample, the first player wins in one move, taking 30 modulo 10. | 2,300 | math | true | false | false | false | false | false | false | false | false | false |
1272B | Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $$$(0, 0)$$$ on an infinite grid. You also have the sequence of instructions of this robot. It is written as the string $$$s$$$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $$$(x, y)$$$ right now, he can move to one of the adjacent cells (depending on the current instruction). If the current instruction is 'L', then the robot can move to the left to $$$(x - 1, y)$$$; if the current instruction is 'R', then the robot can move to the right to $$$(x + 1, y)$$$; if the current instruction is 'U', then the robot can move to the top to $$$(x, y + 1)$$$; if the current instruction is 'D', then the robot can move to the bottom to $$$(x, y - 1)$$$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $$$(0, 0)$$$) twice then it breaks. So the sequence of instructions is valid if the robot starts in the cell $$$(0, 0)$$$, performs the given instructions, visits no cell other than $$$(0, 0)$$$ two or more times and ends the path in the cell $$$(0, 0)$$$. Also cell $$$(0, 0)$$$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $$$(0, 0)$$$) and "UUDD" (the cell $$$(0, 1)$$$ is visited twice). The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain. Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric). You have to answer $$$q$$$ independent test cases. Input The first line of the input contains one integer $$$q$$$ ($$$1 le q le 2 cdot 10^4$$$) — the number of test cases. The next $$$q$$$ lines contain test cases. The $$$i$$$-th test case is given as the string $$$s$$$ consisting of at least $$$1$$$ and no more than $$$10^5$$$ characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions. It is guaranteed that the sum of $$$s$$$ (where $$$s$$$ is the length of $$$s$$$) does not exceed $$$10^5$$$ over all test cases ($$$sum s le 10^5$$$). Output For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $$$t$$$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $$$0$$$, you are allowed to print an empty line (but you can don't print it). | 1,200 | greedy | false | true | false | false | false | false | false | false | false | false |
1062B | JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer $$$n$$$, you can perform the following operations zero or more times: mul $$$x$$$: multiplies $$$n$$$ by $$$x$$$ (where $$$x$$$ is an arbitrary positive integer). sqrt: replaces $$$n$$$ with $$$sqrt{n}$$$ (to apply this operation, $$$sqrt{n}$$$ must be an integer). You can perform these operations as many times as you like. What is the minimum value of $$$n$$$, that can be achieved and what is the minimum number of operations, to achieve that minimum value? Apparently, no one in the class knows the answer to this problem, maybe you can help them? Input The only line of the input contains a single integer $$$n$$$ ($$$1 le n le 10^6$$$)xa0— the initial number. Output Print two integers: the minimum integer $$$n$$$ that can be achieved using the described operations and the minimum number of operations required. Note In the first example, you can apply the operation mul $$$5$$$ to get $$$100$$$ and then sqrt to get $$$10$$$. In the second example, you can first apply sqrt to get $$$72$$$, then mul $$$18$$$ to get $$$1296$$$ and finally two more sqrt and you get $$$6$$$. Note, that even if the initial value of $$$n$$$ is less or equal $$$10^6$$$, it can still become greater than $$$10^6$$$ after applying one or more operations. | 1,500 | math | true | false | false | false | false | false | false | false | false | false |
753A | Problem - 753A - Codeforces =============== xa0 — number of candies Santa Claus has. Output Print to the first line integer number _k_ — maximal number of kids which can get candies. Print to the second line _k_ distinct integer numbers: number of candies for each of _k_ kid. The sum of _k_ printed numbers should be exactly _n_. If there are many solutions, print any of them. Examples Input 5 Output 2 2 3 Input 9 Output 3 3 5 1 Input 2 Output 1 2 Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 10:00:35 (l1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,000 | math | true | false | false | false | false | false | false | false | false | false |
327E | Iahub wants to meet his girlfriend Iahubina. They both live in _Ox_ axis (the horizontal axis). Iahub lives at point 0 and Iahubina at point _d_. Iahub has _n_ positive integers _a_1, _a_2, ..., _a__n_. The sum of those numbers is _d_. Suppose _p_1, _p_2, ..., _p__n_ is a permutation of {1,u20092,u2009...,u2009_n_}. Then, let _b_1u2009=u2009_a__p_1, _b_2u2009=u2009_a__p_2 and so on. The array b is called a "route". There are _n_! different routes, one for each permutation _p_. Iahub's travel schedule is: he walks _b_1 steps on _Ox_ axis, then he makes a break in point _b_1. Then, he walks _b_2 more steps on _Ox_ axis and makes a break in point _b_1u2009+u2009_b_2. Similarly, at _j_-th (1u2009≤u2009_j_u2009≤u2009_n_) time he walks _b__j_ more steps on _Ox_ axis and makes a break in point _b_1u2009+u2009_b_2u2009+u2009...u2009+u2009_b__j_. Iahub is very superstitious and has _k_ integers which give him bad luck. He calls a route "good" if he never makes a break in a point corresponding to one of those _k_ numbers. For his own curiosity, answer how many good routes he can make, modulo 1000000007 (109u2009+u20097). Input The first line contains an integer _n_ (1u2009≤u2009_n_u2009≤u200924). The following line contains _n_ integers: _a_1,u2009_a_2,u2009...,u2009_a__n_ (1u2009≤u2009_a__i_u2009≤u2009109). The third line contains integer _k_ (0u2009≤u2009_k_u2009≤u20092). The fourth line contains _k_ positive integers, representing the numbers that give Iahub bad luck. Each of these numbers does not exceed 109. Note In the first case consider six possible orderings: [2, 3, 5]. Iahub will stop at position 2, 5 and 10. Among them, 5 is bad luck for him. [2, 5, 3]. Iahub will stop at position 2, 7 and 10. Among them, 7 is bad luck for him. [3, 2, 5]. He will stop at the unlucky 5. [3, 5, 2]. This is a valid ordering. [5, 2, 3]. He got unlucky twice (5 and 7). [5, 3, 2]. Iahub would reject, as it sends him to position 5. In the second case, note that it is possible that two different ways have the identical set of stopping. In fact, all six possible ways have the same stops: [2, 4, 6], so there's no bad luck for Iahub. | 2,300 | dp | false | false | false | true | false | false | false | false | false | false |
1621G | You are given the sequence of integers $$$a_1, a_2, ldots, a_n$$$ of length $$$n$$$. The sequence of indices $$$i_1 < i_2 < ldots < i_k$$$ of length $$$k$$$ denotes the subsequence $$$a_{i_1}, a_{i_2}, ldots, a_{i_k}$$$ of length $$$k$$$ of sequence $$$a$$$. The subsequence $$$a_{i_1}, a_{i_2}, ldots, a_{i_k}$$$ of length $$$k$$$ of sequence $$$a$$$ is called increasing subsequence if $$$a_{i_j} < a_{i_{j+1}}$$$ for each $$$1 leq j < k$$$. The weight of the increasing subsequence $$$a_{i_1}, a_{i_2}, ldots, a_{i_k}$$$ of length $$$k$$$ of sequence $$$a$$$ is the number of $$$1 leq j leq k$$$, such that exists index $$$i_k < x leq n$$$ and $$$a_x > a_{i_j}$$$. For example, if $$$a = [6, 4, 8, 6, 5]$$$, then the sequence of indices $$$i = [2, 4]$$$ denotes increasing subsequence $$$[4, 6]$$$ of sequence $$$a$$$. The weight of this increasing subsequence is $$$1$$$, because for $$$j = 1$$$ exists $$$x = 5$$$ and $$$a_5 = 5 > a_{i_1} = 4$$$, but for $$$j = 2$$$ such $$$x$$$ doesn't exist. Find the sum of weights of all increasing subsequences of $$$a$$$ modulo $$$10^9+7$$$. Input The first line contains a single integer $$$t$$$ ($$$1 leq t leq 1000$$$)xa0— the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 leq n leq 2 cdot 10^5$$$)xa0— the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$1 leq a_i leq 10^9$$$)xa0— the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 cdot 10^5$$$. Note In the first test case the following increasing subsequences of $$$a$$$ have not zero weight: The weight of $$$[a_1] = [6]$$$ is $$$1$$$. The weight of $$$[a_2] = [4]$$$ is $$$1$$$. The weight of $$$[a_2, a_3] = [4, 8]$$$ is $$$1$$$. The weight of $$$[a_2, a_4] = [4, 6]$$$ is $$$1$$$. The sum of weights of increasing subsequences is $$$4$$$. In the second test case there are $$$7$$$ increasing subsequences of $$$a$$$ with not zero weight: $$$3$$$ with weight $$$1$$$, $$$3$$$ with weight $$$2$$$ and $$$1$$$ with weight $$$3$$$. The sum of weights is $$$12$$$. | 3,200 | math | true | false | false | false | false | false | false | false | false | false |
802J | Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on. Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank? Heidi's _n_ friends are labeled 0 through _n_u2009-u20091, and their network of connections forms a tree. In other words, every two of her friends _a_, _b_ know each other, possibly indirectly (there is a sequence of friends starting from _a_ and ending on _b_ and such that each two consecutive friends in the sequence know each other directly), and there are exactly _n_u2009-u20091 pairs of friends who know each other directly. Jenny is given the number 0. Input The first line of the input contains the number of friends _n_ (3u2009≤u2009_n_u2009≤u2009100). The next _n_u2009-u20091 lines each contain three space-separated integers _u_, _v_ and _c_ (0u2009≤u2009_u_,u2009_v_u2009≤u2009_n_u2009-u20091, 1u2009≤u2009_c_u2009≤u2009104), meaning that _u_ and _v_ are friends (know each other directly) and the cost for travelling between _u_ and _v_ is _c_. It is guaranteed that the social network of the input forms a tree. Output Output a single integer – the maximum sum of costs. Examples Input 6 1 2 3 0 2 100 1 4 2 0 3 7 3 5 10 Input 11 1 0 1664 2 0 881 3 2 4670 4 2 1555 5 1 1870 6 2 1265 7 2 288 8 7 2266 9 2 1536 10 6 3378 Note In the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then friend 2 sends her to friend 1 (costing Heidi 3), and finally friend 1 relays her to friend 4 (incurring an additional cost of 2). | 1,400 | graphs | false | false | false | false | false | false | false | false | false | true |
1252K | Adding two numbers several times is a time-consuming task, so you want to build a robot. The robot should have a string $$$S = S_1 S_2 dots S_N$$$ of $$$N$$$ characters on its memory that represents addition instructions. Each character of the string, $$$S_i$$$, is either 'A' or 'B'. You want to be able to give $$$Q$$$ commands to the robot, each command is either of the following types: 1 $$$L$$$ $$$R$$$. The robot should toggle all the characters of $$$S_i$$$ where $$$L le i le R$$$. Toggling a character means changing it to 'A' if it was previously 'B', or changing it to 'B' if it was previously 'A'. 2 $$$L$$$ $$$R$$$ $$$A$$$ $$$B$$$. The robot should call $$$f(L, R, A, B)$$$ and return two integers as defined in the following pseudocode: ``` function f(L, R, A, B): FOR i from L to R if S[i] = 'A' A = A + B else B = A + B return (A, B) ``` You want to implement the robot's expected behavior. Input Input begins with a line containing two integers: $$$N$$$ $$$Q$$$ ($$$1 le N, Q le 100,000$$$) representing the number of characters in the robot's memory and the number of commands, respectively. The next line contains a string $$$S$$$ containing $$$N$$$ characters (each either 'A' or 'B') representing the initial string in the robot's memory. The next $$$Q$$$ lines each contains a command of the following types. 1 $$$L$$$ $$$R$$$ ($$$1 le L le R le N$$$) 2 $$$L$$$ $$$R$$$ $$$A$$$ $$$B$$$ ($$$1 le L le R le N$$$; $$$0 le A, B le 10^9$$$) There is at least one command of the second type. Output For each command of the second type in the same order as input, output in a line two integers (separated by a single space), the value of $$$A$$$ and $$$B$$$ returned by $$$f(L, R, A, B)$$$, respectively. As this output can be large, you need to modulo the output by $$$1,000,000,007$$$. Example Input 5 3 ABAAA 2 1 5 1 1 1 3 5 2 2 5 0 1000000000 Note Explanation for the sample input/output #1 For the first command, calling $$$f(L, R, A, B)$$$ causes the following: Initially, $$$A = 1$$$ and $$$B = 1$$$. At the end of $$$i = 1$$$, $$$A = 2$$$ and $$$B = 1$$$. At the end of $$$i = 2$$$, $$$A = 2$$$ and $$$B = 3$$$. At the end of $$$i = 3$$$, $$$A = 5$$$ and $$$B = 3$$$. At the end of $$$i = 4$$$, $$$A = 8$$$ and $$$B = 3$$$. At the end of $$$i = 5$$$, $$$A = 11$$$ and $$$B = 3$$$. Therefore, $$$f(L, R, A, B)$$$ will return $$$(11, 3)$$$. For the second command, string $$$S$$$ will be updated to "ABBBB". For the third command, the value of $$$A$$$ will always be $$$0$$$ and the value of $$$B$$$ will always be $$$1,000,000,000$$$. Therefore, $$$f(L, R, A, B)$$$ will return $$$(0, 1,000,000,000)$$$. | 2,100 | math | true | false | false | false | false | false | false | false | false | false |
1583B | Lord Omkar would like to have a tree with $$$n$$$ nodes ($$$3 le n le 10^5$$$) and has asked his disciples to construct the tree. However, Lord Omkar has created $$$m$$$ ($$$mathbf{1 le m < n}$$$) restrictions to ensure that the tree will be as heavenly as possible. A tree with $$$n$$$ nodes is an connected undirected graph with $$$n$$$ nodes and $$$n-1$$$ edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once. Here is an example of a tree: A restriction consists of $$$3$$$ pairwise distinct integers, $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 le a,b,c le n$$$). It signifies that node $$$b$$$ cannot lie on the simple path between node $$$a$$$ and node $$$c$$$. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 leq t leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$3 leq n leq 10^5$$$, $$$mathbf{1 leq m < n}$$$), representing the size of the tree and the number of restrictions. The $$$i$$$-th of the next $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ ($$$1 le a_i, b_i, c_i le n$$$, $$$a$$$, $$$b$$$, $$$c$$$ are distinct), signifying that node $$$b_i$$$ cannot lie on the simple path between nodes $$$a_i$$$ and $$$c_i$$$. It is guaranteed that the sum of $$$n$$$ across all test cases will not exceed $$$10^5$$$. Output For each test case, output $$$n-1$$$ lines representing the $$$n-1$$$ edges in the tree. On each line, output two integers $$$u$$$ and $$$v$$$ ($$$1 le u, v le n$$$, $$$u eq v$$$) signifying that there is an edge between nodes $$$u$$$ and $$$v$$$. Given edges have to form a tree that satisfies Omkar's restrictions. Example Input 2 7 4 1 2 3 3 4 5 5 6 7 6 5 4 5 3 1 2 3 2 3 4 3 4 5 Output 1 2 1 3 3 5 3 4 2 7 7 6 5 1 1 3 3 2 2 4 Note The output of the first sample case corresponds to the following tree: For the first restriction, the simple path between $$$1$$$ and $$$3$$$ is $$$1, 3$$$, which doesn't contain $$$2$$$. The simple path between $$$3$$$ and $$$5$$$ is $$$3, 5$$$, which doesn't contain $$$4$$$. The simple path between $$$5$$$ and $$$7$$$ is $$$5, 3, 1, 2, 7$$$, which doesn't contain $$$6$$$. The simple path between $$$6$$$ and $$$4$$$ is $$$6, 7, 2, 1, 3, 4$$$, which doesn't contain $$$5$$$. Thus, this tree meets all of the restrictions. The output of the second sample case corresponds to the following tree: | 1,200 | constructive algorithms | false | false | false | false | false | true | false | false | false | false |
1498A | The $$$ ext{$$$gcdSum$$$}$$$ of a positive integer is the $$$gcd$$$ of that integer with its sum of digits. Formally, $$$ ext{$$$gcdSum$$$}(x) = gcd(x, ext{ sum of digits of } x)$$$ for a positive integer $$$x$$$. $$$gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$ — the largest integer $$$d$$$ such that both integers $$$a$$$ and $$$b$$$ are divisible by $$$d$$$. For example: $$$ ext{$$$gcdSum$$$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$$$. Given an integer $$$n$$$, find the smallest integer $$$x ge n$$$ such that $$$ ext{$$$gcdSum$$$}(x) > 1$$$. Input The first line of input contains one integer $$$t$$$ $$$(1 le t le 10^4)$$$ — the number of test cases. Then $$$t$$$ lines follow, each containing a single integer $$$n$$$ $$$(1 le n le 10^{18})$$$. All test cases in one test are different. Note Let us explain the three test cases in the sample. Test case 1: $$$n = 11$$$: $$$ ext{$$$gcdSum$$$}(11) = gcd(11, 1 + 1) = gcd(11, 2) = 1$$$. $$$ ext{$$$gcdSum$$$}(12) = gcd(12, 1 + 2) = gcd(12, 3) = 3$$$. So the smallest number $$$ge 11$$$ whose $$$gcdSum$$$ $$$> 1$$$ is $$$12$$$. Test case 2: $$$n = 31$$$: $$$ ext{$$$gcdSum$$$}(31) = gcd(31, 3 + 1) = gcd(31, 4) = 1$$$. $$$ ext{$$$gcdSum$$$}(32) = gcd(32, 3 + 2) = gcd(32, 5) = 1$$$. $$$ ext{$$$gcdSum$$$}(33) = gcd(33, 3 + 3) = gcd(33, 6) = 3$$$. So the smallest number $$$ge 31$$$ whose $$$gcdSum$$$ $$$> 1$$$ is $$$33$$$. Test case 3: $$$ n = 75$$$: $$$ ext{$$$gcdSum$$$}(75) = gcd(75, 7 + 5) = gcd(75, 12) = 3$$$. The $$$ ext{$$$gcdSum$$$}$$$ of $$$75$$$ is already $$$> 1$$$. Hence, it is the answer. | 800 | math | true | false | false | false | false | false | false | false | false | false |
758C | Problem - 758C - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags binary search constructive algorithms implementation math *1700 No tag edit access → Contest materials ") Editorial") . Output Print three integers: 1. the maximum number of questions a particular pupil is asked, 2. the minimum number of questions a particular pupil is asked, 3. how many times the teacher asked Sergei. Examples Input 1 3 8 1 1 Output 3 2 3 Input 4 2 9 4 2 Output 2 1 1 Input 5 5 25 4 3 Output 1 1 1 Input 100 100 1000000000000000000 100 100 Output 101010101010101 50505050505051 50505050505051 Note The order of asking pupils in the first test: 1. the pupil from the first row who seats at the first table, it means it is Sergei; 2. the pupil from the first row who seats at the second table; 3. the pupil from the first row who seats at the third table; 4. the pupil from the first row who seats at the first table, it means it is Sergei; 5. the pupil from the first row who seats at the second table; 6. the pupil from the first row who seats at the third table; 7. the pupil from the first row who seats at the first table, it means it is Sergei; 8. the pupil from the first row who seats at the second table; The order of asking pupils in the second test: 1. the pupil from the first row who seats at the first table; 2. the pupil from the first row who seats at the second table; 3. the pupil from the second row who seats at the first table; 4. the pupil from the second row who seats at the second table; 5. the pupil from the third row who seats at the first table; 6. the pupil from the third row who seats at the second table; 7. the pupil from the fourth row who seats at the first table; 8. the pupil from the fourth row who seats at the second table, it means it is Sergei; 9. the pupil from the third row who seats at the first table; Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 09:59:11 (j2). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,700 | math | true | false | false | false | false | false | false | false | false | false |
364D | Problem - 364D - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags brute force math probabilities *2900 No tag edit access → Contest materials , that all numbers of the set are evenly divisible by _g_'. Unfortunately Jane couldn't cope with the task and John offered her to find the ghd of the same subset of numbers. Ghd is a positive integer _g_, such that at least half of numbers from the set are evenly divisible by _g_ and there isn't such _g_' (_g_'u2009>u2009_g_) that at least half of the numbers from the set are evenly divisible by _g_'. Jane coped with the task for two hours. Please try it, too. Input The first line contains an integer _n_ (1u2009≤u2009_n_u2009≤u2009106) showing how many numbers are in set _a_. The second line contains space-separated integers _a_1,u2009_a_2,u2009...,u2009_a__n_ (1u2009≤u2009_a__i_u2009≤u20091012). Please note, that given set can contain equal numbers. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the %I64d specifier. Output Print a single integer _g_ — the Ghd of set _a_. Examples Input 6 6 2 3 4 5 6 Output 3 Input 5 5 5 6 10 15 Output 5 Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 11:25:58 (j3). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 2,900 | math | true | false | false | false | false | false | false | false | false | false |
622F | Problem - 622F - Codeforces =============== xa0 ]( "Educational Codeforces Round 7") . Input The only line contains two integers _n_,u2009_k_ (1u2009≤u2009_n_u2009≤u2009109,u20090u2009≤u2009_k_u2009≤u2009106). Output Print the only integer _a_ — the remainder after dividing the value of the sum by the value 109u2009+u20097. Examples Input 4 1 Output 10 Input 4 2 Output 30 Input 4 3 Output 100 Input 4 0 Output 4 Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 10:25:16 (j2). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 2,600 | math | true | false | false | false | false | false | false | false | false | false |
1469A | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS". You are given a sequence $$$s$$$ of $$$n$$$ characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence. You have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced. Determine if it is possible to obtain an RBS after these replacements. Input The first line contains one integer $$$t$$$ ($$$1 le t le 1000$$$) — the number of test cases. Each test case consists of one line containing $$$s$$$ ($$$2 le s le 100$$$) — a sequence of characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence. Output For each test case, print YES if it is possible to obtain a regular bracket sequence, or NO otherwise}. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 5 () (?) (??) ??() )?(? Note In the first test case, the sequence is already an RBS. In the third test case, you can obtain an RBS as follows: ()() or (()). In the fourth test case, you can obtain an RBS as follows: ()(). | 1,000 | greedy | false | true | false | false | false | false | false | false | false | false |
153A | . Output Output _A_u2009+u2009_B_ without leading zeros. Note The code provided in the post about the round doesn't solve the task. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 12:14:10 (h1). Supported by []( | 1,600 | null | false | false | false | false | false | false | false | false | false | false |
774J | Well, the series which Stepan watched for a very long time, ended. In total, the series had _n_ episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to _k_. Input The first line contains two integers _n_ and _k_ (1u2009≤u2009_n_u2009≤u2009100, 0u2009≤u2009_k_u2009≤u2009_n_) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of _n_ symbols "Y", "N" and "?". If the _i_-th symbol equals "Y", Stepan remembers that he has watched the episode number _i_. If the _i_-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number _i_. If the _i_-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number _i_ or not. Output If Stepan's dissatisfaction can be exactly equal to _k_, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because _k_u2009=u20092. In the second test _k_u2009=u20091, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. | 2,000 | dp | false | false | false | true | false | false | false | false | false | false |
335B | Problem - 335B - Codeforces =============== xa0 containing only lowercase English letters. Output If _s_ contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of _s_. If _s_ doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of _s_ and is as long as possible. If there exists multiple answers, you are allowed to print any of them. Examples Input bbbabcbbb Output bbbcbbb Input rquwmzexectvnbanemsmdufrg Output rumenanemur Note A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 11:34:24 (l1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,900 | dp | false | false | false | true | false | false | false | false | false | false |
350B | Valera's finally decided to go on holiday! He packed up and headed for a ski resort. Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has _n_ objects (we will consider the objects indexed in some way by integers from 1 to _n_), each object is either a hotel or a mountain. Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object _v_, the resort has at most one object _u_, such that there is a ski track built from object _u_ to object _v_. We also know that no hotel has got a ski track leading from the hotel to some object. Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects _v_1,u2009_v_2,u2009...,u2009_v__k_ (_k_u2009≥u20091) and meet the following conditions: 1. Objects with numbers _v_1,u2009_v_2,u2009...,u2009_v__k_u2009-u20091 are mountains and the object with number _v__k_ is the hotel. 2. For any integer _i_ (1u2009≤u2009_i_u2009<u2009_k_), there is exactly one ski track leading from object _v__i_. This track goes to object _v__i_u2009+u20091. 3. The path contains as many objects as possible (_k_ is maximal). Help Valera. Find such path that meets all the criteria of our hero! Input The first line contains integer _n_ (1u2009≤u2009_n_u2009≤u2009105) — the number of objects. The second line contains _n_ space-separated integers _type_1,u2009_type_2,u2009...,u2009_type__n_ — the types of the objects. If _type__i_ equals zero, then the _i_-th object is the mountain. If _type__i_ equals one, then the _i_-th object is the hotel. It is guaranteed that at least one object is a hotel. The third line of the input contains _n_ space-separated integers _a_1,u2009_a_2,u2009...,u2009_a__n_ (0u2009≤u2009_a__i_u2009≤u2009_n_) — the description of the ski tracks. If number _a__i_ equals zero, then there is no such object _v_, that has a ski track built from _v_ to _i_. If number _a__i_ doesn't equal zero, that means that there is a track built from object _a__i_ to object _i_. Output In the first line print _k_ — the maximum possible path length for Valera. In the second line print _k_ integers _v_1,u2009_v_2,u2009...,u2009_v__k_ — the path. If there are multiple solutions, you can print any of them. | 1,500 | graphs | false | false | false | false | false | false | false | false | false | true |
513G2 | You are given a permutation of _n_ numbers _p_1,u2009_p_2,u2009...,u2009_p__n_. We perform _k_ operations of the following type: choose uniformly at random two indices _l_ and _r_ (_l_u2009≤u2009_r_) and reverse the order of the elements _p__l_,u2009_p__l_u2009+u20091,u2009...,u2009_p__r_. Your task is to find the expected value of the number of inversions in the resulting permutation. Input The first line of input contains two integers _n_ and _k_ (1u2009≤u2009_n_u2009≤u2009100, 1u2009≤u2009_k_u2009≤u2009109). The next line contains _n_ integers _p_1,u2009_p_2,u2009...,u2009_p__n_ — the given permutation. All _p__i_ are different and in range from 1 to _n_. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem G1 (3 points), the constraints 1u2009≤u2009_n_u2009≤u20096, 1u2009≤u2009_k_u2009≤u20094 will hold. In subproblem G2 (5 points), the constraints 1u2009≤u2009_n_u2009≤u200930, 1u2009≤u2009_k_u2009≤u2009200 will hold. In subproblem G3 (16 points), the constraints 1u2009≤u2009_n_u2009≤u2009100, 1u2009≤u2009_k_u2009≤u2009109 will hold. Output Output the answer with absolute or relative error no more than 1_e_u2009-u20099. Note Consider the first sample test. We will randomly pick an interval of the permutation (1,u20092,u20093) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability we will inverse the first two elements' order and obtain the permutation (2,u20091,u20093) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1,u20093,u20092) with one inversion. Finally, with probability the randomly picked interval will contain all elements, leading to the permutation (3,u20092,u20091) with 3 inversions. Hence, the expected number of inversions is equal to . | 2,400 | dp | false | false | false | true | false | false | false | false | false | false |
923A | Alice and Bob begin their day with a quick game. They first choose a starting number _X_0u2009≥u20093 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the _i_-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number. Formally, he or she selects a prime _p_u2009<u2009_X__i_u2009-u20091 and then finds the minimum _X__i_u2009≥u2009_X__i_u2009-u20091 such that _p_ divides _X__i_. Note that if the selected prime _p_ already divides _X__i_u2009-u20091, then the number does not change. Eve has witnessed the state of the game after two turns. Given _X_2, help her determine what is the smallest possible starting number _X_0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions. Input The input contains a single integer _X_2 (4u2009≤u2009_X_2u2009≤u2009106). It is guaranteed that the integer _X_2 is composite, that is, is not prime. Output Output a single integerxa0— the minimum possible _X_0. Note In the first test, the smallest possible starting number is _X_0u2009=u20096. One possible course of the game is as follows: Alice picks prime 5 and announces _X_1u2009=u200910 Bob picks prime 7 and announces _X_2u2009=u200914. In the second case, let _X_0u2009=u200915. Alice picks prime 2 and announces _X_1u2009=u200916 Bob picks prime 5 and announces _X_2u2009=u200920. | 1,700 | math | true | false | false | false | false | false | false | false | false | false |
1922E | Let's recall that an increasing subsequence of the array $$$a$$$ is a sequence that can be obtained from it by removing some elements without changing the order of the remaining elements, and the remaining elements are strictly increasing (i.u2009e $$$a_{b_1} < a_{b_2} < dots < a_{b_k}$$$ and $$$b_1 < b_2 < dots < b_k$$$). Note that an empty subsequence is also increasing. You are given a positive integer $$$X$$$. Your task is to find an array of integers of length at most $$$200$$$, such that it has exactly $$$X$$$ increasing subsequences, or report that there is no such array. If there are several answers, you can print any of them. If two subsequences consist of the same elements, but correspond to different positions in the array, they are considered different (for example, the array $$$[2, 2]$$$ has two different subsequences equal to $$$[2]$$$). Input The first line contains a single integer $$$t$$$ ($$$1 le t le 1000$$$)xa0— the number of test cases. The only line of each test case contains a single integer $$$X$$$ ($$$2 le X le 10^{18}$$$). Output For each query, print the answer to it. If it is impossible to find the required array, print -1 on the first line. Otherwise, print a positive integer $$$n$$$ on the first linexa0— the length of the array. On the second line, print $$$n$$$ integersxa0— the required array itself. If there are several answers, you can print any of them. All elements of the array should be in the range $$$[-10^9; 10^9]$$$. Example Output 1 0 3 0 1 0 5 2 2 3 4 2 7 -1 -1 0 0 2 3 -1 | 1,800 | math | true | false | false | false | false | false | false | false | false | false |
1382B | There are $$$n$$$ piles of stones, where the $$$i$$$-th pile has $$$a_i$$$ stones. Two people play a game, where they take alternating turns removing stones. In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game. Input The first line contains a single integer $$$t$$$ ($$$1le tle 1000$$$) xa0— the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1le nle 10^5$$$) xa0— the number of piles. The second line of each test case contains $$$n$$$ integers $$$a_1,ldots,a_n$$$ ($$$1le a_ile 10^9$$$) xa0— $$$a_i$$$ is equal to the number of stones in the $$$i$$$-th pile. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$. Output For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second". Example Input 7 3 2 5 4 8 1 1 1 1 1 1 1 1 6 1 2 3 4 5 6 6 1 1 2 1 2 2 1 1000000000 5 1 2 2 1 1 3 1 1 1 Output First Second Second First First Second First Note In the first test case, the first player will win the game. His winning strategy is: 1. The first player should take the stones from the first pile. He will take $$$1$$$ stone. The numbers of stones in piles will be $$$[1, 5, 4]$$$. 2. The second player should take the stones from the first pile. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 5, 4]$$$. 3. The first player should take the stones from the second pile because the first pile is empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 1, 4]$$$. 4. The second player should take the stones from the second pile because the first pile is empty. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 0, 4]$$$. 5. The first player should take the stones from the third pile because the first and second piles are empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 0, 0]$$$. 6. The second player will lose the game because all piles will be empty. | 1,100 | dp | false | false | false | true | false | false | false | false | false | false |
828A | In a small restaurant there are _a_ tables for one person and _b_ tables for two persons. It it known that _n_ groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group. If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group. You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to. Input The first line contains three integers _n_, _a_ and _b_ (1u2009≤u2009_n_u2009≤u20092·105, 1u2009≤u2009_a_,u2009_b_u2009≤u20092·105) — the number of groups coming to the restaurant, the number of one-seater and the number of two-seater tables. The second line contains a sequence of integers _t_1,u2009_t_2,u2009...,u2009_t__n_ (1u2009≤u2009_t__i_u2009≤u20092) — the description of clients in chronological order. If _t__i_ is equal to one, then the _i_-th group consists of one person, otherwise the _i_-th group consists of two people. Output Print the total number of people the restaurant denies service to. Note In the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. The third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, all clients are served. In the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, it occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients. | 1,200 | implementation | false | false | true | false | false | false | false | false | false | false |
460C | Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted _n_ flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions. There are _m_ days left to the birthday. The height of the _i_-th flower (assume that the flowers in the row are numbered from 1 to _n_ from left to right) is equal to _a__i_ at the moment. At each of the remaining _m_ days the beaver can take a special watering and water _w_ contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get? Input The first line contains space-separated integers _n_, _m_ and _w_ (1u2009≤u2009_w_u2009≤u2009_n_u2009≤u2009105;xa01u2009≤u2009_m_u2009≤u2009105). The second line contains space-separated integers _a_1,u2009_a_2,u2009...,u2009_a__n_ (1u2009≤u2009_a__i_u2009≤u2009109). Output Print a single integer — the maximum final height of the smallest flower. Note In the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test. | 1,700 | greedy | false | true | false | false | false | false | false | false | false | false |
587B | Problem - 587B - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags dp *2100 No tag edit access → Contest materials ") array, _a_0,u2009...,u2009_a__n_u2009-u20091 that _b_ can be build from _a_ with formula: _b__i_u2009=u2009_a__i_ _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 _b__i_1,u2009_b__i_2,u2009...,u2009_b__i__x_ (0u2009≤u2009_i_1u2009<u2009_i_2u2009<u2009...u2009<u2009_i__x_u2009<u2009_l_), such that: 1u2009≤u2009_x_u2009≤u2009_k_ For each 1u2009≤u2009_j_u2009≤u2009_x_u2009-u20091, For each 1u2009≤u2009_j_u2009≤u2009_x_u2009-u20091, _b__i__j_u2009≤u2009_b__i__j_u2009+u20091. i.e this subsequence is non-decreasing. Since this number can be very large, she want to know it modulo 109u2009+u20097. Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number. Input The first line of input contains three integers, _n_,u2009_l_ and _k_ (1u2009≤u2009_n_,u2009_k_, _n_u2009×u2009_k_u2009≤u2009106 and 1u2009≤u2009_l_u2009≤u20091018). The second line contains _n_ space separated integers, _a_0,u2009_a_1,u2009...,u2009_a__n_u2009-u20091 (1u2009≤u2009_a__i_u2009≤u2009109 for each 0u2009≤u2009_i_u2009≤u2009_n_u2009-u20091). Output Print the answer modulo 1u2009000u2009000u2009007 in one line. Examples Input 3 5 3 5 9 1 Output 10 Input 5 10 3 1 2 3 4 5 Output 25 Note In the first sample case, . So all such sequences are: , , , , , , , , and . Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 10:32:47 (g1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 2,100 | dp | false | false | false | true | false | false | false | false | false | false |
500F | Dohyun is running a grocery store. He sells _n_ items numbered by integers from 1 to _n_. The _i_-th (1u2009≤u2009_i_u2009≤u2009_n_) of them costs _c__i_ dollars, and if I buy it, my happiness increases by _h__i_. Each item can be displayed only for _p_ units of time because of freshness. As Dohyun displays the _i_-th item at time _t__i_, the customers can buy the _i_-th item only from time _t__i_ to time _t__i_u2009+u2009(_p_u2009-u20091) inclusively. Also, each customer cannot buy the same item more than once. I'd like to visit Dohyun's grocery store and buy some items for the New Year Party, and maximize my happiness. Because I am a really busy person, I can visit the store only once, and for very short period of time. In other words, if I visit the store at time _t_, I can only buy the items available at time _t_. But I can buy as many items as possible, if the budget holds. I can't buy same item several times due to store rules. It is not necessary to use the whole budget. I made a list of _q_ pairs of integers (_a__j_,u2009_b__j_), which means I may visit the store at time _a__j_, and spend at most _b__j_ dollars at the store. For each pair, I'd like to know the maximum happiness I can obtain. But there are so many pairs that I can't handle them. Can you help me? Input The first line contains two space-separated integers _n_ and _p_ (1u2009≤u2009_n_u2009≤u20094000, 1u2009≤u2009_p_u2009≤u200910u2009000) — the number of items, and the display time of each item. Next _n_ lines describe the items. The _i_-th (1u2009≤u2009_i_u2009≤u2009_n_) of them contains three space-separated integers _c__i_, _h__i_, _t__i_ (1u2009≤u2009_c__i_,u2009_h__i_u2009≤u20094000, 1u2009≤u2009_t__i_u2009≤u200910u2009000) — the cost of the _i_-th item, the happiness of the _i_-th item, and the time when the _i_-th item starts to be displayed. The next line contains an integer _q_ (1u2009≤u2009_q_u2009≤u200920u2009000)— the number of candidates. Next _q_ lines describe the candidates. The _j_-th (1u2009≤u2009_j_u2009≤u2009_q_) of them contains two space-separated integers _a__j_, _b__j_ (1u2009≤u2009_a__j_u2009≤u200920u2009000, 1u2009≤u2009_b__j_u2009≤u20094000) — the visit time and the budget for _j_-th visit of store. Output For each candidate, print a single line containing the maximum happiness that I can obtain by buying some items. Examples Input 4 4 2 3 2 3 5 1 4 7 2 11 15 5 4 1 3 2 5 2 6 5 14 Input 5 4 3 2 1 7 4 4 2 1 2 6 3 5 3 2 2 10 1 5 2 5 4 8 4 9 4 10 5 8 5 9 5 10 8 4 7 9 Note Consider the first sample. 1. At time 1, only the 2nd item is available. I can buy the 2nd item using 3 dollars and my happiness will increase by 5. 2. At time 2, the 1st, 2nd, and 3rd item is available. I can buy the 1st item using 2 dollars, and the 2nd item using 3 dollars. My happiness will increase by 3 + 5 = 8. 3. At time 2, the 1st, 2nd, and 3rd item is available. I can buy the 1st item using 2 dollars, and the 3nd item using 4 dollars. My happiness will increase by 3 + 7 = 10. 4. At time 5, the 1st, 3rd, and 4th item is available. I can buy the 1st item using 2 dollars, and the 4th item using 11 dollars. My happiness will increase by 3 + 15 = 18. Note that I don't need to use the whole budget in this case. | 2,700 | dp | false | false | false | true | false | false | false | false | false | false |
909F | Problem - 909F - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags constructive algorithms *2500 No tag edit access → Contest materials ") Editorial") . Output For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and _N_ elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. Examples Input 3 Output NO NO Input 6 Output YES 6 5 4 3 2 1 YES 3 6 2 5 1 4 Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 09:22:56 (g1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 2,500 | constructive algorithms | false | false | false | false | false | true | false | false | false | false |
868E | You are given a tree (a connected non-oriented graph without cycles) with vertices numbered from 1 to _n_, and the length of the _i_-th edge is _w__i_. In the vertex _s_ there is a policeman, in the vertices _x_1,u2009_x_2,u2009...,u2009_x__m_ (_x__j_u2009≠u2009_s_) _m_ criminals are located. The policeman can walk along the edges with speed 1, the criminals can move with arbitrary large speed. If a criminal at some moment is at the same point as the policeman, he instantly gets caught by the policeman. Determine the time needed for the policeman to catch all criminals, assuming everybody behaves optimally (i.e. the criminals maximize that time, the policeman minimizes that time). Everybody knows positions of everybody else at any moment of time. Input The first line contains single integer _n_ (1u2009≤u2009_n_u2009≤u200950)xa0— the number of vertices in the tree. The next _n_u2009-u20091 lines contain three integers each: _u__i_, _v__i_, _w__i_ (1u2009≤u2009_u__i_,u2009_v__i_u2009≤u2009_n_, 1u2009≤u2009_w__i_u2009≤u200950) denoting edges and their lengths. It is guaranteed that the given graph is a tree. The next line contains single integer _s_ (1u2009≤u2009_s_u2009≤u2009_n_)xa0— the number of vertex where the policeman starts. The next line contains single integer _m_ (1u2009≤u2009_m_u2009≤u200950)xa0— the number of criminals. The next line contains _m_ integers _x_1,u2009_x_2,u2009...,u2009_x__m_ (1u2009≤u2009_x__j_u2009≤u2009_n_, _x__j_u2009≠u2009_s_)xa0— the number of vertices where the criminals are located. _x__j_ are not necessarily distinct. Output If the policeman can't catch criminals, print single line "Terrorists win" (without quotes). Otherwise, print single integerxa0— the time needed to catch all criminals. Examples Input 4 1 2 2 1 3 1 1 4 1 2 4 3 1 4 1 Input 6 1 2 3 2 3 5 3 4 1 3 5 4 2 6 3 2 3 1 3 5 Note In the first example one of the optimal scenarios is the following. The criminal number 2 moves to vertex 3, the criminal 4xa0— to vertex 4. The policeman goes to vertex 4 and catches two criminals. After that the criminal number 1 moves to the vertex 2. The policeman goes to vertex 3 and catches criminal 2, then goes to the vertex 2 and catches the remaining criminal. | 2,700 | dp | false | false | false | true | false | false | false | false | false | false |
1510B | You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has $$$d$$$ buttons with digits from $$$0$$$ to $$$d - 1$$$. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" buttonxa0— pressing it pops up all other buttons. Initially, no buttons are pushed down. The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are $$$n$$$ possible passwords for this particular lock. Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted. Input The first line contains two integers $$$d$$$ and $$$n$$$ ($$$1 le d le 10$$$; $$$1 le n le 2^d - 1$$$). Next $$$n$$$ lines describe possible passwords. Each line contains a string $$$s_i$$$ of $$$d$$$ zeros and ones: for all $$$j$$$ from $$$1$$$ to $$$d$$$ the $$$j$$$-th character is 1 iff the button with the digit $$$j - 1$$$ must be pushed down. All strings $$$s_i$$$ are different, and each string contains at least one 1. Output On the first line, print the number $$$k$$$xa0— the minimum number of button presses. On the second line, print $$$k$$$ tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press "RESET", print "R". Note In the second example, the sequence 1 2 R 2 0 1 is also possible. | 2,600 | graphs | false | false | false | false | false | false | false | false | false | true |
1670E | After the last regional contest, Hemose and his teammates finally qualified to the ICPC World Finals, so for this great achievement and his love of trees, he gave you this problem as the name of his team "Hemose 3al shagra" (Hemose on the tree). You are given a tree of $$$n$$$ vertices where $$$n$$$ is a power of $$$2$$$. You have to give each node and edge an integer value in the range $$$. Input The first line contains a single integer $$$t$$$ ($$$1 le t le 5cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$p$$$ ($$$1 le p le 17$$$), where $$$n$$$ (the number of vertices in the tree) is equal to $$$2^p$$$. Each of the next $$$n−1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 le u,v le n$$$) meaning that there is an edge between the vertices $$$u$$$ and $$$v$$$ in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3cdot 10^5$$$. Output For each test case on the first line print the chosen root. On the second line, print $$$n$$$ integers separated by spaces, where the $$$i$$$-th integer represents the chosen value for the $$$i$$$-th node. On the third line, print $$$n-1$$$ integers separated by spaces, where the $$$i$$$-th integer represents the chosen value for the $$$i$$$-th edge. The edges are numerated in the order of their appearance in the input data. If there are multiple solutions, you may output any. Example Input 2 2 1 2 2 3 3 4 3 1 2 2 3 3 4 1 5 1 6 5 7 5 8 Output 3 5 1 3 6 4 2 7 5 1 2 8 11 4 13 9 15 6 14 3 7 10 5 12 Note The tree in the first test case with the weights of all nodes and edges is shown in the picture. The costs of all paths are: $$$3$$$; $$$3oplus 7=4$$$; $$$3oplus 7oplus 6=2$$$; $$$3oplus 2=1$$$; $$$3oplus 2oplus 1=0$$$; $$$3oplus 2oplus 1oplus 4=4$$$; $$$3oplus 2oplus 1oplus 4oplus 5=1$$$. The maximum cost of all these paths is $$$4$$$. We can show that it is impossible to assign the values and choose the root differently to achieve a smaller maximum cost of all paths. The tree in the second test case: | 2,200 | constructive algorithms | false | false | false | false | false | true | false | false | false | false |
447B | Problem - 447B - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags greedy implementation *1000 No tag edit access → Contest materials ") ") Editorial") he represents its value with a function _f_(_s_), where Now DZY has a string _s_. He wants to insert _k_ lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get? Input The first line contains a single string _s_xa0(1u2009≤u2009_s_u2009≤u2009103). The second line contains a single integer _k_xa0(0u2009≤u2009_k_u2009≤u2009103). The third line contains twenty-six integers from _w__a_ to _w__z_. Each such number is non-negative and doesn't exceed 1000. Output Print a single integer — the largest possible value of the resulting string DZY could get. Examples Input abc 3 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 41 Note In the test sample DZY can obtain "abcbbc", _value_u2009=u20091·1u2009+u20092·2u2009+u20093·2u2009+u20094·2u2009+u20095·2u2009+u20096·2u2009=u200941. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 11:02:38 (k3). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,000 | greedy | false | true | false | false | false | false | false | false | false | false |
730L | A simplified arithmetic expression (SAE) is an arithmetic expression defined by the following grammar: <SAE> ::= <Number> <SAE>+<SAE> <SAE>*<SAE> (<SAE>) <Number> ::= <Digit> <Digit><Number> <Digit> ::= 0 1 2 3 4 5 6 7 8 9 In other words it's a correct arithmetic expression that is allowed to contain brackets, numbers (possibly with leading zeros), multiplications and additions. For example expressions "(0+01)", "0" and "1*(0)" are simplified arithmetic expressions, but expressions "2-1", "+1" and "1+2)" are not. Given a string _s_1_s_2..._s__s_ that represents a SAE; _s__i_ denotes the _i_-th character of the string which can be either a digit ('0'-'9'), a plus sign ('+'), a multiplication sign ('*'), an opening round bracket '(' or a closing round bracket ')'. A part _s__l__s__l_u2009+u20091..._s__r_ of this string is called a sub-expression if and only if it is a SAE. You task is to answer _m_ queries, each of which is a pair of integers _l__i_, _r__i_ (1u2009≤u2009_l__i_u2009≤u2009_r__i_u2009≤u2009_s_). For each query determine whether the corresponding part of the given string is a sub-expression and in case it's a sub-expression calculate its value modulo 1000000007xa0(109u2009+u20097). The values should be calculated using standard operator priorities. Input The first line of the input contains non-empty string _s_ (1u2009≤u2009_s_u2009≤u20094·105) which represents a correct SAE. Each character of the string can be one of the following characters: '*', '+', '(', ')' or a digit ('0'-'9'). The expression might contain extra-huge numbers. The second line contains an integer _m_ (1u2009≤u2009_m_u2009≤u20094·105) which is the number of queries. Each of the next _m_ lines contains two space-separated integers _l__i_, _r__i_ (1u2009≤u2009_l__i_u2009≤u2009_r__i_u2009≤u2009_s_) — the _i_-th query. Output The _i_-th number of output should be the answer for the _i_-th query. If the _i_-th query corresponds to a valid sub-expression output the value of the sub-expression modulo 1000000007xa0(109u2009+u20097). Otherwise output -1 as an answer for the query. Print numbers on separate lines. Examples Input ((1+2)*3+101*2) 6 8 14 1 6 2 10 11 14 5 5 4 5 | 3,200 | data structures | false | false | false | false | true | false | false | false | false | false |
1705B | Mark is cleaning a row of $$$n$$$ rooms. The $$$i$$$-th room has a nonnegative dust level $$$a_i$$$. He has a magical cleaning machine that can do the following three-step operation. Select two indices $$$i<j$$$ such that the dust levels $$$a_i$$$, $$$a_{i+1}$$$, $$$dots$$$, $$$a_{j-1}$$$ are all strictly greater than $$$0$$$. Set $$$a_i$$$ to $$$a_i-1$$$. Set $$$a_j$$$ to $$$a_j+1$$$. Mark's goal is to make $$$a_1 = a_2 = ldots = a_{n-1} = 0$$$ so that he can nicely sweep the $$$n$$$-th room. Determine the minimum number of operations needed to reach his goal. Input The first line contains a single integer $$$t$$$ ($$$1leq tleq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2leq nleq 2cdot 10^5$$$) — the number of rooms. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0leq a_ileq 10^9$$$) — the dust level of each room. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2cdot 10^5$$$. Output For each test case, print a line containing a single integer — the minimum number of operations. It can be proven that there is a sequence of operations that meets the goal. Example Input 4 3 2 0 0 5 0 2 0 2 0 6 2 0 3 0 4 6 4 0 0 0 10 Note In the first case, one possible sequence of operations is as follows. Choose $$$i=1$$$ and $$$j=2$$$, yielding the array $$$[1,1,0]$$$. Choose $$$i=1$$$ and $$$j=3$$$, yielding the array $$$[0,1,1]$$$. Choose $$$i=2$$$ and $$$j=3$$$, yielding the array $$$[0,0,2]$$$. At this point, $$$a_1=a_2=0$$$, completing the process. In the second case, one possible sequence of operations is as follows. Choose $$$i=4$$$ and $$$j=5$$$, yielding the array $$$[0,2,0,1,1]$$$. Choose $$$i=2$$$ and $$$j=3$$$, yielding the array $$$[0,1,1,1,1]$$$. Choose $$$i=2$$$ and $$$j=5$$$, yielding the array $$$[0,0,1,1,2]$$$. Choose $$$i=3$$$ and $$$j=5$$$, yielding the array $$$[0,0,0,1,3]$$$. Choose $$$i=4$$$ and $$$j=5$$$, yielding the array $$$[0,0,0,0,4]$$$. In the last case, the array already satisfies the condition. | 900 | greedy | false | true | false | false | false | false | false | false | false | false |
1517B | The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town. There are $$$n+1$$$ checkpoints on the trail. They are numbered by $$$0$$$, $$$1$$$, ..., $$$n$$$. A runner must start at checkpoint $$$0$$$ and finish at checkpoint $$$n$$$. No checkpoint is skippablexa0— he must run from checkpoint $$$0$$$ to checkpoint $$$1$$$, then from checkpoint $$$1$$$ to checkpoint $$$2$$$ and so on. Look at the picture in notes section for clarification. Between any two adjacent checkpoints, there are $$$m$$$ different paths to choose. For any $$$1le ile n$$$, to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$, a runner can choose exactly one from the $$$m$$$ possible paths. The length of the $$$j$$$-th path between checkpoint $$$i-1$$$ and $$$i$$$ is $$$b_{i,j}$$$ for any $$$1le jle m$$$ and $$$1le ile n$$$. To test the trail, we have $$$m$$$ runners. Each runner must run from the checkpoint $$$0$$$ to the checkpoint $$$n$$$ once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length $$$l_i$$$ between checkpoint $$$i-1$$$ and $$$i$$$ ($$$1le ile n$$$), his tiredness is $$$$$$min_{i=1}^n l_i,$$$$$$ i.xa0e. the minimum length of the paths he takes. Please arrange the paths of the $$$m$$$ runners to minimize the sum of tiredness of them. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 10,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 leq n,m leq 100$$$). The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$b_{i,1}$$$, $$$b_{i,2}$$$, ..., $$$b_{i,m}$$$ ($$$1 le b_{i,j} le 10^9$$$). It is guaranteed that the sum of $$$ncdot m$$$ over all test cases does not exceed $$$10^4$$$. Output For each test case, output $$$n$$$ lines. The $$$j$$$-th number in the $$$i$$$-th line should contain the length of the path that runner $$$j$$$ chooses to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$. There should be exactly $$$m$$$ integers in the $$$i$$$-th line and these integers should form a permuatation of $$$b_{i, 1}$$$, ..., $$$b_{i, m}$$$ for all $$$1le ile n$$$. If there are multiple answers, print any. Example Input 2 2 3 2 3 4 1 3 5 3 2 2 3 4 1 3 5 Output 2 3 4 5 3 1 2 3 4 1 3 5 Note In the first case, the sum of tiredness is $$$min(2,5) + min(3,3) + min(4,1) = 6$$$. In the second case, the sum of tiredness is $$$min(2,4,3) + min(3,1,5) = 3$$$. | 1,200 | greedy | false | true | false | false | false | false | false | false | false | false |
1158D | Vasya has $$$n$$$ different points $$$A_1, A_2, ldots A_n$$$ on the plane. No three of them lie on the same line He wants to place them in some order $$$A_{p_1}, A_{p_2}, ldots, A_{p_n}$$$, where $$$p_1, p_2, ldots, p_n$$$xa0— some permutation of integers from $$$1$$$ to $$$n$$$. After doing so, he will draw oriented polygonal line on these points, drawing oriented segments from each point to the next in the chosen order. So, for all $$$1 leq i leq n-1$$$ he will draw oriented segment from point $$$A_{p_i}$$$ to point $$$A_{p_{i+1}}$$$. He wants to make this polygonal line satisfying $$$2$$$ conditions: it will be non-self-intersecting, so any $$$2$$$ segments which are not neighbors don't have common points. it will be winding. Vasya has a string $$$s$$$, consisting of $$$(n-2)$$$ symbols "L" or "R". Let's call an oriented polygonal line winding, if its $$$i$$$-th turn left, if $$$s_i = $$$ "L" and right, if $$$s_i = $$$ "R". More formally: $$$i$$$-th turn will be in point $$$A_{p_{i+1}}$$$, where oriented segment from point $$$A_{p_i}$$$ to point $$$A_{p_{i+1}}$$$ changes to oriented segment from point $$$A_{p_{i+1}}$$$ to point $$$A_{p_{i+2}}$$$. Let's define vectors $$$overrightarrow{v_1} = overrightarrow{A_{p_i} A_{p_{i+1}}}$$$ and $$$overrightarrow{v_2} = overrightarrow{A_{p_{i+1}} A_{p_{i+2}}}$$$. Then if in order to rotate the vector $$$overrightarrow{v_1}$$$ by the smallest possible angle, so that its direction coincides with the direction of the vector $$$overrightarrow{v_2}$$$ we need to make a turn counterclockwise, then we say that $$$i$$$-th turn is to the left, and otherwise to the right. For better understanding look at this pictures with some examples of turns: There are left turns on this picture There are right turns on this picture You are given coordinates of the points $$$A_1, A_2, ldots A_n$$$ on the plane and string $$$s$$$. Find a permutation $$$p_1, p_2, ldots, p_n$$$ of the integers from $$$1$$$ to $$$n$$$, such that the polygonal line, drawn by Vasya satisfy two necessary conditions. Input The first line contains one integer $$$n$$$xa0— the number of points ($$$3 leq n leq 2000$$$). Next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$, divided by spacexa0— coordinates of the point $$$A_i$$$ on the plane ($$$-10^9 leq x_i, y_i leq 10^9$$$). The last line contains a string $$$s$$$ consisting of symbols "L" and "R" with length $$$(n-2)$$$. It is guaranteed that all points are different and no three points lie at the same line. Output If the satisfying permutation doesn't exists, print $$$-1$$$. In the other case, print $$$n$$$ numbers $$$p_1, p_2, ldots, p_n$$$xa0— the permutation which was found ($$$1 leq p_i leq n$$$ and all $$$p_1, p_2, ldots, p_n$$$ are different). If there exists more than one solution, you can find any. Note This is the picture with the polygonal line from the $$$1$$$ test: As we see, this polygonal line is non-self-intersecting and winding, because the turn in point $$$2$$$ is left. This is the picture with the polygonal line from the $$$2$$$ test: | 2,600 | math | true | false | false | false | false | false | false | false | false | false |
1A | Problem - 1A - Codeforces =============== xa0 ]( "85") . Output Write the needed number of flagstones. Examples Input 6 6 4 Output 4 Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 12:54:58 (f1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,000 | math | true | false | false | false | false | false | false | false | false | false |
1188D | Problem - 1188D - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags dp *3100 No tag edit access → Contest materials . The second line contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$0 le a_i le 10^{17}$$$). Output Output exactly one integerxa0— the smallest number of operations we need to perform to make all $$$n$$$ numbers equal. Examples Input 4 228 228 228 228 Output 0 Input 3 2 2 8 Output 3 Note In the first example, all numbers are already equal. So the needed number of operation is $$$0$$$. In the second example, we can apply the operation $$$3$$$ times: add $$$8$$$ to first $$$2$$$, add $$$8$$$ to second $$$2$$$, add $$$2$$$ to $$$8$$$, making all numbers equal to $$$10$$$. It can be proved that we can't make all numbers equal in less than $$$3$$$ operations. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 06:45:16 (i1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 3,100 | dp | false | false | false | true | false | false | false | false | false | false |
14A | Problem - 14A - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags implementation *800 No tag edit access → Contest materials ") sheet with _n_ rows and _m_ columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides. Input The first line of the input data contains numbers _n_ and _m_ (1u2009≤u2009_n_,u2009_m_u2009≤u200950), _n_ — amount of lines, and _m_ — amount of columns on Bob's sheet. The following _n_ lines contain _m_ characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square. Output Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better. Examples Input 6 7 ....... ..***.. ..*.... ..***.. ..*.... ..***.. Output ** *.. ** *.. ** Input 3 3 ** *. ** Output ** *. ** Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 12:51:51 (j2). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 800 | implementation | false | false | true | false | false | false | false | false | false | false |
916C | Problem - 916C - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags constructive algorithms graphs shortest paths *1600 No tag edit access → Contest materials Editorial") of the graph is a prime number. The graph contains no loops or multi-edges. If you are not familiar with some terms from the statement you can find definitions of them in notes section. Help Jamie construct any graph with given number of vertices and edges that is interesting! Input First line of input contains 2 integers _n_, _m_ xa0— the required number of vertices and edges. Output In the first line output 2 integers _sp_, _mstw_ (1u2009≤u2009_sp_,u2009_mstw_u2009≤u20091014)xa0— the length of the shortest path and the sum of edges' weights in the minimum spanning tree. In the next _m_ lines output the edges of the graph. In each line output 3 integers _u_, _v_, _w_ (1u2009≤u2009_u_,u2009_v_u2009≤u2009_n_,u20091u2009≤u2009_w_u2009≤u2009109) describing the edge connecting _u_ and _v_ and having weight _w_. Examples Input 4 4 Output 7 7 1 2 3 2 3 2 3 4 2 2 4 4 Input 5 4 Output 7 13 1 2 2 1 3 4 1 4 3 4 5 4 Note The graph of sample 1: Shortest path sequence: {1,u20092,u20093,u20094}. MST edges are marked with an asterisk (*). Definition of terms used in the problem statement: A shortest path in an undirected graph is a sequence of vertices (_v_1,u2009_v_2,u2009... ,u2009_v__k_) such that _v__i_ is adjacent to _v__i_u2009+u20091 1u2009≤u2009_i_u2009<u2009_k_ and the sum of weight is minimized where _w_(_i_,u2009_j_) is the edge weight between _i_ and _j_. ( Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 09:21:06 (h1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,600 | constructive algorithms | false | false | false | false | false | true | false | false | false | false |
1849B | Monocarp is playing yet another computer game. And yet again, his character is killing some monsters. There are $$$n$$$ monsters, numbered from $$$1$$$ to $$$n$$$, and the $$$i$$$-th of them has $$$a_i$$$ health points initially. Monocarp's character has an ability that deals $$$k$$$ damage to the monster with the highest current health. If there are several of them, the one with the smaller index is chosen. If a monster's health becomes less than or equal to $$$0$$$ after Monocarp uses his ability, then it dies. Monocarp uses his ability until all monsters die. Your task is to determine the order in which monsters will die. Input The first line contains a single integer $$$t$$$ ($$$1 le t le 10^4$$$)xa0— the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 le n le 3 cdot 10^5$$$; $$$1 le k le 10^9$$$)xa0— the number of monsters and the damage which Monocarp's ability deals. The second line contains $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$1 le a_i le 10^9$$$)xa0— the initial health points of monsters. The sum of $$$n$$$ over all test cases doesn't exceed $$$3 cdot 10^5$$$. Note In the first example, the health points change as follows: $$$[1, 2, underline{3}] ightarrow [1, underline{2}, 1] ightarrow [underline{1}, 0, 1] ightarrow [-1, 0, underline{1}] ightarrow [-1, 0, -1]$$$. The monster that is going to take damage the next time Monocarp uses his ability is underlined. In the second example, the health points change as follows: $$$[underline{1}, 1] ightarrow [-2, underline{1}] ightarrow [-2, -2]$$$. In the third example, the health points change as follows: $$$[2, underline{8}, 3, 5] ightarrow [2, underline{5}, 3, 5] ightarrow [2, 2, 3, underline{5}] ightarrow [2, 2, underline{3}, 2] ightarrow [underline{2}, 2, 0, 2] ightarrow [-1, underline{2}, 0, 2] ightarrow [-1, -1, 0, underline{2}] ightarrow [-1, -1, 0, -1]$$$. | 1,000 | math | true | false | false | false | false | false | false | false | false | false |
1720D2 | It is the hard version of the problem. The only difference is that in this version $$$a_i le 10^9$$$. You are given an array of $$$n$$$ integers $$$a_0, a_1, a_2, ldots a_{n - 1}$$$. Bryap wants to find the longest beautiful subsequence in the array. An array $$$b = xa0— the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 leq n leq 3 cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,...,a_{n-1}$$$ ($$$0 leq a_i leq 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 cdot 10^5$$$. Note In the first test case, we can pick the whole array as a beautiful subsequence because $$$1 oplus 1 < 2 oplus 0$$$. In the second test case, we can pick elements with indexes $$$1$$$, $$$2$$$ and $$$4$$$ (in $$$0$$$ indexation). For this elements holds: $$$2 oplus 2 < 4 oplus 1$$$ and $$$4 oplus 4 < 1 oplus 2$$$. | 2,400 | dp | false | false | false | true | false | false | false | false | false | false |
643A | Bear Limak has _n_ colored balls, arranged in one long row. Balls are numbered 1 through _n_, from left to right. There are _n_ possible colors, also numbered 1 through _n_. The _i_-th ball has color _t__i_. For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant. There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. Input The first line of the input contains a single integer _n_ (1u2009≤u2009_n_u2009≤u20095000)xa0— the number of balls. The second line contains _n_ integers _t_1,u2009_t_2,u2009...,u2009_t__n_ (1u2009≤u2009_t__i_u2009≤u2009_n_) where _t__i_ is the color of the _i_-th ball. Output Print _n_ integers. The _i_-th of them should be equal to the number of intervals where _i_ is a dominant color. Note In the first sample, color 2 is dominant in three intervals: An interval [2,u20092] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4,u20094] contains one ball, with color 2 again. An interval [2,u20094] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | 1,500 | implementation | false | false | true | false | false | false | false | false | false | false |
1211E | Polycarp recently became an employee of the company "Double Permutation Inc." Now he is a fan of permutations and is looking for them everywhere! A permutation in this problem is a sequence of integers $$$p_1, p_2, dots, p_k$$$ such that every integer from $$$1$$$ to $$$k$$$ occurs exactly once in it. For example, the following sequences are permutations of $$$[3, 1, 4, 2]$$$, $$$[1]$$$ and $$$[6, 1, 2, 3, 5, 4]$$$. The following sequences are not permutations: $$$[0, 1]$$$, $$$[1, 2, 2]$$$, $$$[1, 2, 4]$$$ and $$$[2, 3]$$$. In the lobby of the company's headquarter statistics on visits to the company's website for the last $$$n$$$ days are published — the sequence $$$a_1, a_2, dots, a_n$$$. Polycarp wants to color all the elements of this sequence in one of three colors (red, green or blue) so that: all red numbers, being written out of $$$a_1, a_2, dots, a_n$$$ from left to right (that is, without changing their relative order), must form some permutation (let's call it $$$P$$$); all green numbers, being written out of $$$a_1, a_2, dots, a_n$$$ from left to right (that is, without changing their relative order), must form the same permutation $$$P$$$; among blue numbers there should not be elements that are equal to some element of the permutation $$$P$$$. Help Polycarp to color all $$$n$$$ numbers so that the total number of red and green elements is maximum. Input The first line contains an integer $$$n$$$ ($$$1 le n le 2cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$1 le a_i le 2cdot10^5$$$). Output Print a string $$$s$$$ of length $$$n$$$ such that: $$$s_i$$$='R', if the element $$$a_i$$$ must be colored in red; $$$s_i$$$='G', if the element $$$a_i$$$ must be colored in green; $$$s_i$$$='B', if the element $$$a_i$$$ must be colored in blue. The string $$$s$$$ should maximize the total number of red and green elements when fulfilling the requirements from the main part of the problem statement. If there are several optimal answers, print any of them. | 2,000 | greedy | false | true | false | false | false | false | false | false | false | false |
1418A | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order. Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. You have to answer $$$t$$$ independent test cases. Input The first line of the input contains one integer $$$t$$$ ($$$1 le t le 2 cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 le x le 10^9$$$; $$$1 le y, k le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. Output For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. Example Input 5 2 1 5 42 13 24 12 11 12 1000000000 1000000000 1000000000 2 1000000000 1000000000 Output 14 33 25 2000000003 1000000001999999999 | 1,000 | math | true | false | false | false | false | false | false | false | false | false |
1422B | A matrix of size $$$n imes m$$$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $$$(a_1, a_2, dots , a_k)$$$ is a palindrome, if for any integer $$$i$$$ ($$$1 le i le k$$$) the equality $$$a_i = a_{k - i + 1}$$$ holds. Sasha owns a matrix $$$a$$$ of size $$$n imes m$$$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs. Help him! Input The first line contains a single integer $$$t$$$xa0— the number of test cases ($$$1 le t le 10$$$). The $$$t$$$ tests follow. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 le n, m le 100$$$)xa0— the size of the matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i, j}$$$ ($$$0 le a_{i, j} le 10^9$$$)xa0— the elements of the matrix. Output For each test output the smallest number of operations required to make the matrix nice. Example Input 2 4 2 4 2 2 4 4 2 2 4 3 4 1 2 3 4 5 6 7 8 9 10 11 18 Note In the first test case we can, for example, obtain the following nice matrix in $$$8$$$ operations: 2 2 4 4 4 4 2 2 In the second test case we can, for example, obtain the following nice matrix in $$$42$$$ operations: 5 6 6 5 6 6 6 6 5 6 6 5 | 1,300 | math | true | false | false | false | false | false | false | false | false | false |
1182A | Problem - 1182A - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags dp math *1000 No tag edit access → Contest materials xa0— the length. Output Print the number of ways to fill. Examples Input 4 Output 4 Input 1 Output 0 Note In the first example, there are $$$4$$$ possible cases of filling. In the second example, you cannot fill the shapes in $$$3 imes 1$$$ tiles. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 06:47:34 (l3). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,000 | math | true | false | false | false | false | false | false | false | false | false |
616C | You are given a rectangular field of _n_u2009×u2009_m_ cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side. Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component. For each impassable cell (_x_,u2009_y_) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (_x_,u2009_y_). You should do it for each impassable cell independently. The answer should be printed as a matrix with _n_ rows and _m_ columns. The _j_-th symbol of the _i_-th row should be "." if the cell is empty at the start. Otherwise the _j_-th symbol of the _i_-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces. To make your output faster it is recommended to build the output as an array of _n_ strings having length _m_ and print it as a sequence of lines. It will be much faster than writing character-by-character. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Input The first line contains two integers _n_,u2009_m_ (1u2009≤u2009_n_,u2009_m_u2009≤u20091000) — the number of rows and columns in the field. Each of the next _n_ lines contains _m_ symbols: "." for empty cells, "*" for impassable cells. Output Print the answer as a matrix as described above. See the examples to precise the format of the output. Examples Input 4 5 **.. ..** .*.*. *.*. Output 46..3 ..732 .6.4. 5.4.3 Note In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner). | 1,600 | null | false | false | false | false | false | false | false | false | false | false |
613B | Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly _n_ skills. Each skill is represented by a non-negative integer _a__i_xa0— the current skill level. All skills have the same maximum level _A_. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: The number of skills that a character has perfected (i.e., such that _a__i_u2009=u2009_A_), multiplied by coefficient _c__f_. The minimum skill level among all skills (_min_ _a__i_), multiplied by coefficient _c__m_. Now Lesha has _m_ hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to _A_ yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers _n_, _A_, _c__f_, _c__m_ and _m_ (1u2009≤u2009_n_u2009≤u2009100u2009000, 1u2009≤u2009_A_u2009≤u2009109, 0u2009≤u2009_c__f_,u2009_c__m_u2009≤u20091000, 0u2009≤u2009_m_u2009≤u20091015). The second line contains exactly _n_ integers _a__i_ (0u2009≤u2009_a__i_u2009≤u2009_A_), separated by spaces,xa0— the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than _m_ currency units. On the second line print _n_ integers _a_'_i_ (_a__i_u2009≤u2009_a_'_i_u2009≤u2009_A_), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than _m_ currency units. Numbers should be separated by spaces. Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum. | 1,900 | greedy | false | true | false | false | false | false | false | false | false | false |
1036C | Problem - 1036C - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags combinatorics dp *1900 No tag edit access → Contest materials — the number of segments in a testcase. Each of the next $$$T$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$1 le L_i le R_i le 10^{18}$$$). Output Print $$$T$$$ lines — the $$$i$$$-th line should contain the number of classy integers on a segment $$$ Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 08:14:32 (l1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,900 | dp | false | false | false | true | false | false | false | false | false | false |
652A | The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height _h_1 cm from the ground. On the height _h_2 cm (_h_2u2009>u2009_h_1) on the same tree hung an apple and the caterpillar was crawling to the apple. Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by _a_ cm per hour by day and slips down by _b_ cm per hour by night. In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm. Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple. Input The first line contains two integers _h_1,u2009_h_2 (1u2009≤u2009_h_1u2009<u2009_h_2u2009≤u2009105) — the heights of the position of the caterpillar and the apple in centimeters. The second line contains two integers _a_,u2009_b_ (1u2009≤u2009_a_,u2009_b_u2009≤u2009105) — the distance the caterpillar goes up by day and slips down by night, in centimeters per hour. Output Print the only integer _k_ — the number of days Gabriel should wait to return to the forest and see the caterpillar getting the apple. If the caterpillar can't get the apple print the only integer u2009-u20091. Note In the first example at 10 pm of the first day the caterpillar gets the height 26. At 10 am of the next day it slips down to the height 14. And finally at 6 pm of the same day the caterpillar gets the apple. Note that in the last example the caterpillar was slipping down under the ground and getting the apple on the next day. | 1,400 | math | true | false | false | false | false | false | false | false | false | false |
1132D | Berland SU holds yet another training contest for its students today. $$$n$$$ students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers! Let students be numbered from $$$1$$$ to $$$n$$$. Laptop of the $$$i$$$-th student has charge $$$a_i$$$ at the beginning of the contest and it uses $$$b_i$$$ of charge per minute (i.e. if the laptop has $$$c$$$ charge at the beginning of some minute, it becomes $$$c - b_i$$$ charge at the beginning of the next minute). The whole contest lasts for $$$k$$$ minutes. Polycarp (the coach of Berland SU) decided to buy a single charger so that all the students would be able to successfully finish the contest. He buys the charger at the same moment the contest starts. Polycarp can choose to buy the charger with any non-negative (zero or positive) integer power output. The power output is chosen before the purchase, it can't be changed afterwards. Let the chosen power output be $$$x$$$. At the beginning of each minute (from the minute contest starts to the last minute of the contest) he can plug the charger into any of the student's laptops and use it for some integer number of minutes. If the laptop is using $$$b_i$$$ charge per minute then it will become $$$b_i - x$$$ per minute while the charger is plugged in. Negative power usage rate means that the laptop's charge is increasing. The charge of any laptop isn't limited, it can become infinitely large. The charger can be plugged in no more than one laptop at the same time. The student successfully finishes the contest if the charge of his laptop never is below zero at the beginning of some minute (from the minute contest starts to the last minute of the contest, zero charge is allowed). The charge of the laptop of the minute the contest ends doesn't matter. Help Polycarp to determine the minimal possible power output the charger should have so that all the students are able to successfully finish the contest. Also report if no such charger exists. Input The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 le n le 2 cdot 10^5$$$, $$$1 le k le 2 cdot 10^5$$$) — the number of students (and laptops, correspondigly) and the duration of the contest in minutes. The second line contains $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$1 le a_i le 10^{12}$$$) — the initial charge of each student's laptop. The third line contains $$$n$$$ integers $$$b_1, b_2, dots, b_n$$$ ($$$1 le b_i le 10^7$$$) — the power usage of each student's laptop. Output Print a single non-negative integer — the minimal possible power output the charger should have so that all the students are able to successfully finish the contest. If no such charger exists, print -1. Note Let's take a look at the state of laptops in the beginning of each minute on the first example with the charger of power $$$5$$$: 1. charge: $$$[3, 2]$$$, plug the charger into laptop 1; 2. charge: $$$[3 - 4 + 5, 2 - 2] = [4, 0]$$$, plug the charger into laptop 2; 3. charge: $$$[4 - 4, 0 - 2 + 5] = [0, 3]$$$, plug the charger into laptop 1; 4. charge: $$$[0 - 4 + 5, 3 - 2] = [1, 1]$$$. The contest ends after the fourth minute. However, let's consider the charger of power $$$4$$$: 1. charge: $$$[3, 2]$$$, plug the charger into laptop 1; 2. charge: $$$[3 - 4 + 4, 2 - 2] = [3, 0]$$$, plug the charger into laptop 2; 3. charge: $$$[3 - 4, 0 - 2 + 4] = [-1, 2]$$$, the first laptop has negative charge, thus, the first student doesn't finish the contest. In the fourth example no matter how powerful the charger is, one of the students won't finish the contest. | 2,300 | greedy | false | true | false | false | false | false | false | false | false | false |
1775C | Petya and his friend, robot Petya++, like to solve exciting math problems. One day Petya++ came up with the numbers $$$n$$$ and $$$x$$$ and wrote the following equality on the board: $$$$$$n & (n+1) & dots & m = x,$$$$$$ where $$$&$$$ denotes the that the equality on the board holds. Unfortunately, Petya couldn't solve this problem in his head and decided to ask for computer help. He quickly wrote a program and found the answer. Can you solve this difficult problem? Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 2000$$$). The description of the test cases follows. The only line of each test case contains two integers $$$n$$$, $$$x$$$ ($$$0le n, x le 10^{18}$$$). Output For every test case, output the smallest possible value of $$$m$$$ such that equality holds. If the equality does not hold for any $$$m$$$, print $$$-1$$$ instead. We can show that if the required $$$m$$$ exists, it does not exceed $$$5 cdot 10^{18}$$$. Example Input 5 10 8 10 10 10 42 20 16 1000000000000000000 0 Output 12 10 -1 24 1152921504606846976 Note In the first example, $$$10 & 11 = 10$$$, but $$$10 & 11 & 12 = 8$$$, so the answer is $$$12$$$. In the second example, $$$10 = 10$$$, so the answer is $$$10$$$. In the third example, we can see that the required $$$m$$$ does not exist, so we have to print $$$-1$$$. | 1,600 | math | true | false | false | false | false | false | false | false | false | false |
2013D | Zhan, tired after the contest, gave the only task that he did not solve during the contest to his friend, Sungat. However, he could not solve it either, so we ask you to try to solve this problem. You are given an array $$$a_1, a_2, ldots, a_n$$$ of length $$$n$$$. We can perform any number (possibly, zero) of operations on the array. In one operation, we choose a position $$$i$$$ ($$$1 leq i leq n - 1$$$) and perform the following action: $$$a_i := a_i - 1$$$, and $$$a_{i+1} := a_{i+1} + 1$$$. Find the minimum possible value of $$$max(a_1, a_2, ldots, a_n) - min(a_1, a_2, ldots, a_n)$$$. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 10^5$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 leq n leq 2 cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$1 leq a_i leq 10^{12}$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 cdot 10^5$$$. Output For each test case, output a single integer: the minimum possible value of $$$max(a_1, a_2, ldots, a_n) - min(a_1, a_2, ldots, a_n)$$$. Example Input 5 1 1 3 1 2 3 4 4 1 2 3 4 4 2 3 1 5 5 14 4 10 2 Note In the third testcase, you can perform the operation twice with $$$i = 1$$$. After that, the array is $$$a = [2, 3, 2, 3]$$$, and $$$max(2, 3, 2, 3) - min(2, 3, 2, 3) = 3 - 2 = 1$$$. | 1,900 | greedy | false | true | false | false | false | false | false | false | false | false |
748A | Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are _n_ lanes of _m_ desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to _n_ from the left to the right, the desks in a lane are numbered from 1 to _m_ starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture). The organizers numbered all the working places from 1 to 2_nm_. The places are numbered by lanes (i.xa0e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i.xa0e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. The picture illustrates the first and the second samples. Santa Clause knows that his place has number _k_. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right! Input The only line contains three integers _n_, _m_ and _k_ (1u2009≤u2009_n_,u2009_m_u2009≤u200910u2009000, 1u2009≤u2009_k_u2009≤u20092_nm_)xa0— the number of lanes, the number of desks in each lane and the number of Santa Claus' place. Output Print two integers: the number of lane _r_, the number of desk _d_, and a character _s_, which stands for the side of the desk Santa Claus. The character _s_ should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right. Note The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example. In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right. | 800 | math | true | false | false | false | false | false | false | false | false | false |
214B | Problem - 214B - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags brute force constructive algorithms greedy math *1600 No tag edit access → Contest materials — the number of digits in the set. The second line contains _n_ digits, the digits are separated by a single space. Output On a single line print the answer to the problem. If such number does not exist, then you should print -1. Examples Input 1 0 Output 0 Input 11 3 4 5 4 5 3 5 3 4 4 0 Output 5554443330 Input 8 3 2 5 1 5 2 2 3 Output -1 Note In the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. Copyright 2010-2024 Mike Mirzayanov The only programming contests Web 2.0 platform Server time: Nov/30/2024 11:57:06 (i1). Desktop version, switch to [mobile version]( Policy]( by []( User lists Name --- | 1,600 | math | true | false | false | false | false | false | false | false | false | false |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 6