problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
A. Oath of the Night's Watchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?InputFirst line consists of a single integer n (1 ≤ n ≤ 105) — the number of stewards with Jon Snow.Second line consists of n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) representing the values assigned to the stewards.OutputOutput a single integer representing the number of stewards which Jon will feed.ExamplesInput21 5Output0Input31 2 5Output1NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.
Input21 5
Output0
2 seconds
256 megabytes
['constructive algorithms', 'sortings', '*900']
E. Change-freetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudent Arseny likes to plan his life for n days ahead. He visits a canteen every day and he has already decided what he will order in each of the following n days. Prices in the canteen do not change and that means Arseny will spend ci rubles during the i-th day.There are 1-ruble coins and 100-ruble notes in circulation. At this moment, Arseny has m coins and a sufficiently large amount of notes (you can assume that he has an infinite amount of them). Arseny loves modern technologies, so he uses his credit card everywhere except the canteen, but he has to pay in cash in the canteen because it does not accept cards.Cashier always asks the student to pay change-free. However, it's not always possible, but Arseny tries to minimize the dissatisfaction of the cashier. Cashier's dissatisfaction for each of the days is determined by the total amount of notes and coins in the change. To be precise, if the cashier gives Arseny x notes and coins on the i-th day, his dissatisfaction for this day equals x·wi. Cashier always gives change using as little coins and notes as possible, he always has enough of them to be able to do this. "Caution! Angry cashier" Arseny wants to pay in such a way that the total dissatisfaction of the cashier for n days would be as small as possible. Help him to find out how he needs to pay in each of the n days!Note that Arseny always has enough money to pay, because he has an infinite amount of notes. Arseny can use notes and coins he received in change during any of the following days.InputThe first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 109) — the amount of days Arseny planned his actions for and the amount of coins he currently has. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the amounts of money in rubles which Arseny is going to spend for each of the following days. The third line contains a sequence of integers w1, w2, ..., wn (1 ≤ wi ≤ 105) — the cashier's dissatisfaction coefficients for each of the following days.OutputIn the first line print one integer — minimum possible total dissatisfaction of the cashier.Then print n lines, the i-th of then should contain two numbers — the amount of notes and the amount of coins which Arseny should use to pay in the canteen on the i-th day.Of course, the total amount of money Arseny gives to the casher in any of the days should be no less than the amount of money he has planned to spend. It also shouldn't exceed 106 rubles: Arseny never carries large sums of money with him.If there are multiple answers, print any of them.ExamplesInput5 42117 71 150 243 2001 1 1 1 1Output791 171 02 02 432 0Input3 0100 50 501 3 2Output1501 01 00 50Input5 42117 71 150 243 2005 4 3 2 1Output2301 171 01 503 02 0
Input5 42117 71 150 243 2001 1 1 1 1
Output791 171 02 02 432 0
1 second
256 megabytes
['greedy', '*2400']
D. Cartons of milktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlya likes milk very much. She drinks k cartons of milk each day if she has at least k and drinks all of them if she doesn't. But there's an issue — expiration dates. Each carton has a date after which you can't drink it (you still can drink it exactly at the date written on the carton). Due to this, if Olya's fridge contains a carton past its expiry date, she throws it away.Olya hates throwing out cartons, so when she drinks a carton, she chooses the one which expires the fastest. It's easy to understand that this strategy minimizes the amount of cartons thrown out and lets her avoid it if it's even possible. Milk. Best before: 20.02.2017. The main issue Olya has is the one of buying new cartons. Currently, there are n cartons of milk in Olya's fridge, for each one an expiration date is known (how soon does it expire, measured in days). In the shop that Olya visited there are m cartons, and the expiration date is known for each of those cartons as well.Find the maximum number of cartons Olya can buy so that she wouldn't have to throw away any cartons. Assume that Olya drank no cartons today. InputIn the first line there are three integers n, m, k (1 ≤ n, m ≤ 106, 1 ≤ k ≤ n + m) — the amount of cartons in Olya's fridge, the amount of cartons in the shop and the number of cartons Olya drinks each day.In the second line there are n integers f1, f2, ..., fn (0 ≤ fi ≤ 107) — expiration dates of the cartons in Olya's fridge. The expiration date is expressed by the number of days the drinking of this carton can be delayed. For example, a 0 expiration date means it must be drunk today, 1 — no later than tomorrow, etc.In the third line there are m integers s1, s2, ..., sm (0 ≤ si ≤ 107) — expiration dates of the cartons in the shop in a similar format.OutputIf there's no way for Olya to drink the cartons she already has in her fridge, print -1.Otherwise, in the first line print the maximum number x of cartons which Olya can buy so that she wouldn't have to throw a carton away. The next line should contain exactly x integers — the numbers of the cartons that should be bought (cartons are numbered in an order in which they are written in the input, starting with 1). Numbers should not repeat, but can be in arbitrary order. If there are multiple correct answers, print any of them.ExamplesInput3 6 21 0 12 0 2 0 0 2Output31 2 3Input3 1 20 0 01Output-1Input2 1 20 10Output11 NoteIn the first example k = 2 and Olya has three cartons with expiry dates 0, 1 and 1 (they expire today, tomorrow and tomorrow), and the shop has 3 cartons with expiry date 0 and 3 cartons with expiry date 2. Olya can buy three cartons, for example, one with the expiry date 0 and two with expiry date 2.In the second example all three cartons Olya owns expire today and it means she would have to throw packets away regardless of whether she buys an extra one or not.In the third example Olya would drink k = 2 cartons today (one she alreay has in her fridge and one from the shop) and the remaining one tomorrow.
Input3 6 21 0 12 0 2 0 0 2
Output31 2 3
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'sortings', 'two pointers', '*2100']
C. Garlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp. Help Dima to find a suitable way to cut the garland, or determine that this is impossible.While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.InputThe first line contains single integer n (3 ≤ n ≤ 106) — the number of lamps in the garland.Then n lines follow. The i-th of them contain the information about the i-th lamp: the number lamp ai, it is hanging on (and 0, if is there is no such lamp), and its temperature ti ( - 100 ≤ ti ≤ 100). The lamps are numbered from 1 to n.OutputIf there is no solution, print -1.Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them.ExamplesInput62 40 54 22 11 14 2Output1 4Input62 40 64 22 11 14 2Output-1NoteThe garland and cuts scheme for the first example:
Input62 40 54 22 11 14 2
Output1 4
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'trees', '*2000']
B. The Queuetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFinally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.He knows that the receptionist starts working after ts minutes have passed after midnight and closes after tf minutes have passed after midnight (so that (tf - 1) is the last minute when the receptionist is still working). The receptionist spends exactly t minutes on each person in the queue. If the receptionist would stop working within t minutes, he stops serving visitors (other than the one he already serves). Vasya also knows that exactly n visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately. "Reception 1" For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them.Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!InputThe first line contains three integers: the point of time when the receptionist begins to work ts, the point of time when the receptionist stops working tf and the time the receptionist spends on each visitor t. The second line contains one integer n — the amount of visitors (0 ≤ n ≤ 100 000). The third line contains positive integers in non-decreasing order — the points of time when the visitors arrive to the passport office.All times are set in minutes and do not exceed 1012; it is guaranteed that ts < tf. It is also guaranteed that Vasya can arrive at the passport office at such a point of time that he would be served by the receptionist.OutputPrint single non-negative integer — the point of time when Vasya should arrive at the passport office. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and queues up the last. If there are many answers, you can print any of them.ExamplesInput10 15 2210 13Output12Input8 17 343 4 5 8Output2NoteIn the first example the first visitor comes exactly at the point of time when the receptionist begins to work, and he is served for two minutes. At 12 minutes after the midnight the receptionist stops serving the first visitor, and if Vasya arrives at this moment, he will be served immediately, because the next visitor would only come at 13 minutes after midnight.In the second example, Vasya has to come before anyone else to be served.
Input10 15 2210 13
Output12
1 second
256 megabytes
['brute force', 'greedy', '*2100']
A. Snacktowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAccording to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.InputThe first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n. OutputPrint n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.ExamplesInput33 1 2Output3 2 1Input54 5 1 2 3Output 5 4  3 2 1NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.
Input33 1 2
Output3 2 1
2 seconds
256 megabytes
['data structures', 'implementation', '*1100']
E. Mahmoud and a xor triptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n - 1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.We define the distance from city x to city y as the xor of numbers attached to the cities on the path from x to y (including both x and y). In other words if values attached to the cities on the path from x to y form an array p of length l then the distance between them is , where is bitwise xor operation.Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities.InputThe first line contains integer n (1 ≤ n ≤ 105) — the number of cities in Mahmoud and Ehab's country.Then the second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106) which represent the numbers attached to the cities. Integer ai is attached to the city i.Each of the next n  -  1 lines contains two integers u and v (1  ≤  u,  v  ≤  n, u  ≠  v), denoting that there is an undirected road between cities u and v. It's guaranteed that you can reach any city from any other using these roads.OutputOutput one number denoting the total distance between all pairs of cities.ExamplesInput31 2 31 22 3Output10Input51 2 3 4 51 22 33 43 5Output52Input510 9 8 7 61 22 33 43 5Output131NoteA bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.In the first sample the available paths are: city 1 to itself with a distance of 1, city 2 to itself with a distance of 2, city 3 to itself with a distance of 3, city 1 to city 2 with a distance of , city 1 to city 3 with a distance of , city 2 to city 3 with a distance of . The total distance between all pairs of cities equals 1 + 2 + 3 + 3 + 0 + 1 = 10.
Input31 2 31 22 3
Output10
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'data structures', 'dfs and similar', 'dp', 'math', 'trees', '*2100']
D. Mahmoud and a Dictionarytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.InputThe first line of input contains three integers n, m and q (2 ≤ n ≤ 105, 1 ≤ m, q ≤ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.Then m lines follow, each of them contains an integer t (1 ≤ t ≤ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.OutputFirst, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.See the samples for better understanding.ExamplesInput3 3 4hate love like1 love like2 love hate1 hate likelove likelove hatelike hatehate likeOutputYESYESNO1222Input8 6 5hi welcome hello ihateyou goaway dog cat rat1 hi welcome1 ihateyou goaway2 hello ihateyou2 hi goaway2 hi hello1 hi hellodog catdog hihi helloihateyou goawaywelcome ihateyouOutputYESYESYESYESNOYES33112
Input3 3 4hate love like1 love like2 love hate1 hate likelove likelove hatelike hatehate like
OutputYESYESNO1222
4 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'dsu', 'graphs', '*2000']
C. Mahmoud and a Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than ai. For example, if a1 = 2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not.Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a1 = 2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.A substring of string s is a string that consists of some consecutive characters from string s, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself.While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions: How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 109 + 7. What is the maximum length of a substring that can appear in some valid splitting? What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa".InputThe first line contains an integer n (1 ≤ n ≤ 103) denoting the length of the message.The second line contains the message s of length n that consists of lowercase English letters.The third line contains 26 integers a1, a2, ..., a26 (1 ≤ ax ≤ 103) — the maximum lengths of substring each letter can appear in.OutputPrint three lines.In the first line print the number of ways to split the message into substrings and fulfill the conditions mentioned in the problem modulo 109  +  7.In the second line print the length of the longest substring over all the ways.In the third line print the minimum number of substrings over all the ways.ExamplesInput3aab2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1Output322Input10abcdeabcde5 5 5 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1Output40143NoteIn the first example the three ways to split the message are: a|a|b aa|b a|ab The longest substrings are "aa" and "ab" of length 2.The minimum number of substrings is 2 in "a|ab" or "aa|b".Notice that "aab" is not a possible splitting because the letter 'a' appears in a substring of length 3, while a1 = 2.
Input3aab2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output322
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'strings', '*1700']
B. Mahmoud and a Triangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.InputThe first line contains single integer n (3 ≤ n ≤ 105) — the number of line segments Mahmoud has.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the lengths of line segments Mahmoud has.OutputIn the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise.ExamplesInput51 5 3 2 4OutputYESInput34 1 2OutputNONoteFor the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle.
Input51 5 3 2 4
OutputYES
2 seconds
256 megabytes
['constructive algorithms', 'geometry', 'greedy', 'math', 'number theory', 'sortings', '*1000']
A. Mahmoud and Longest Uncommon Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.InputThe first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.OutputIf there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.ExamplesInputabcddefghOutput5InputaaOutput-1NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Inputabcddefgh
Output5
2 seconds
256 megabytes
['constructive algorithms', 'strings', '*1000']
G. Math, math everywheretime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIf you have gone that far, you'll probably skip unnecessary legends anyway...You are given a binary string and an integer . Find the number of integers k, 0 ≤ k < N, such that for all i = 0, 1, ..., m - 1 Print the answer modulo 109 + 7.InputIn the first line of input there is a string s consisting of 0's and 1's (1 ≤ |s| ≤ 40).In the next line of input there is an integer n (1 ≤ n ≤ 5·105).Each of the next n lines contains two space-separated integers pi, αi (1 ≤ pi, αi ≤ 109, pi is prime). All pi are distinct.OutputA single integer — the answer to the problem.ExamplesInput122 13 1Output2Input0123 25 1Output15Input101113 1000000000Output411979884
Input122 13 1
Output2
5 seconds
512 megabytes
['brute force', 'dp', 'math', 'meet-in-the-middle', 'number theory', '*3200']
F. Souvenirstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputArtsem is on vacation and wants to buy souvenirs for his two teammates. There are n souvenir shops along the street. In i-th shop Artsem can buy one souvenir for ai dollars, and he cannot buy more than one souvenir in one shop. He doesn't want to introduce envy in his team, so he wants to buy two souvenirs with least possible difference in price.Artsem has visited the shopping street m times. For some strange reason on the i-th day only shops with numbers from li to ri were operating (weird? yes it is, but have you ever tried to come up with a reasonable legend for a range query problem?). For each visit, Artsem wants to know the minimum possible difference in prices of two different souvenirs he can buy in the opened shops.In other words, for each Artsem's visit you should find the minimum possible value of |as - at| where li ≤ s, t ≤ ri, s ≠ t.InputThe first line contains an integer n (2 ≤ n ≤ 105).The second line contains n space-separated integers a1, ..., an (0 ≤ ai ≤ 109).The third line contains the number of queries m (1 ≤ m ≤ 3·105).Next m lines describe the queries. i-th of these lines contains two space-separated integers li and ri denoting the range of shops working on i-th day (1 ≤ li < ri ≤ n).OutputPrint the answer to each query in a separate line.ExampleInput83 1 4 1 5 9 2 641 81 34 85 7Output0113
Input83 1 4 1 5 9 2 641 81 34 85 7
Output0113
3 seconds
512 megabytes
['data structures', '*3100']
E. Tree Foldingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.InputThe first line of input contains the number of vertices n (2 ≤ n ≤ 2·105).Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.OutputIf it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.ExamplesInput61 22 32 44 51 6Output3Input71 21 33 41 55 66 7Output-1NoteIn the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
Input61 22 32 44 51 6
Output3
2 seconds
512 megabytes
['dfs and similar', 'dp', 'greedy', 'implementation', 'trees', '*2200']
D. Artsem and Saunderstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputArtsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all , and h(g(x)) = f(x) for all , or determine that finding these is impossible.InputThe first line contains an integer n (1 ≤ n ≤ 105).The second line contains n space-separated integers — values f(1), ..., f(n) (1 ≤ f(i) ≤ n).OutputIf there is no answer, print one integer -1.Otherwise, on the first line print the number m (1 ≤ m ≤ 106). On the second line print n numbers g(1), ..., g(n). On the third line print m numbers h(1), ..., h(m).If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions.ExamplesInput31 2 3Output31 2 31 2 3Input32 2 2Output11 1 12Input22 1Output-1
Input31 2 3
Output31 2 31 2 3
2 seconds
512 megabytes
['constructive algorithms', 'dsu', 'math', '*1700']
C. Table Tennis Game 2time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMisha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible.Note that the game consisted of several complete sets.InputThe first line contains three space-separated integers k, a and b (1 ≤ k ≤ 109, 0 ≤ a, b ≤ 109, a + b > 0).OutputIf the situation is impossible, print a single number -1. Otherwise, print the maximum possible number of sets.ExamplesInput11 11 5Output1Input11 2 3Output-1NoteNote that the rules of the game in this problem differ from the real table tennis game, for example, the rule of "balance" (the winning player has to be at least two points ahead to win a set) has no power within the present problem.
Input11 11 5
Output1
2 seconds
512 megabytes
['math', '*1200']
B. Code obfuscationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.InputIn the only line of input there is a string S of lowercase English letters (1 ≤ |S| ≤ 500) — the identifiers of a program with removed whitespace characters.OutputIf this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".ExamplesInputabacabaOutputYESInputjinotegaOutputNONoteIn the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program: replace all occurences of number with a, the result would be "a string a character a string a", replace all occurences of string with b, the result would be "a b a character a b a", replace all occurences of character with c, the result would be "a b a c a b a", all identifiers have been replaced, thus the obfuscation is finished.
Inputabacaba
OutputYES
2 seconds
512 megabytes
['greedy', 'implementation', 'strings', '*1100']
A. Neverending competitionstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: this list contains all Jinotega's flights in this year (in arbitrary order), Jinotega has only flown from his hometown to a snooker contest and back, after each competition Jinotega flies back home (though they may attend a competition in one place several times), and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location!InputIn the first line of input there is a single integer n: the number of Jinotega's flights (1 ≤ n ≤ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport.It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement.OutputIf Jinotega is now at home, print "home" (without quotes), otherwise print "contest".ExamplesInput4SVOSVO->CDGLHR->SVOSVO->LHRCDG->SVOOutputhomeInput3SVOSVO->HKTHKT->SVOSVO->RAPOutputcontestNoteIn the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list.
Input4SVOSVO->CDGLHR->SVOSVO->LHRCDG->SVO
Outputhome
2 seconds
512 megabytes
['implementation', 'math', '*900']
B. Timofey and cubestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYoung Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.InputThe first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.OutputPrint n integers, separated by spaces — the numbers written on the cubes in their initial order.It can be shown that the answer is unique.ExamplesInput74 3 7 6 9 1 2Output2 3 9 6 7 1 4Input86 1 4 2 5 6 9 2Output2 1 6 2 5 4 9 6NoteConsider the first sample. At the begining row was [2, 3, 9, 6, 7, 1, 4]. After first operation row was [4, 1, 7, 6, 9, 3, 2]. After second operation row was [4, 3, 9, 6, 7, 1, 2]. After third operation row was [4, 3, 7, 6, 9, 1, 2]. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].
Input74 3 7 6 9 1 2
Output2 3 9 6 7 1 4
1 second
256 megabytes
['constructive algorithms', 'implementation', '*900']
A. Taymyr is calling youtime limit per test1 secondmemory limit per test255 megabytesinputstandard inputoutputstandard outputComrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day consists of minutes 1, 2, ..., z. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.InputThe only string contains three integers — n, m and z (1 ≤ n, m, z ≤ 104).OutputPrint single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls.ExamplesInput1 1 10Output10Input1 2 5Output2Input2 3 9Output1NoteTaymyr is a place in the north of Russia.In the first test the artists come each minute, as well as the calls, so we need to kill all of them.In the second test we need to kill artists which come on the second and the fourth minutes.In the third test — only the artist which comes on the sixth minute.
Input1 1 10
Output10
1 second
255 megabytes
['brute force', 'implementation', 'math', '*800']
E. Timofey and our friends animalstime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter his birthday party, Timofey went to his favorite tree alley in a park. He wants to feed there his favorite birds — crows.It's widely known that each tree is occupied by a single crow family. The trees in the alley form a row and are numbered from 1 to n. Some families are friends to each other. For some reasons, two families can be friends only if they live not too far from each other, more precisely, there is no more than k - 1 trees between any pair of friend families. Formally, the family on the u-th tree and the family on the v-th tree can be friends only if |u - v| ≤ k holds.One of the friendship features is that if some family learns that Timofey is feeding crows somewhere, it notifies about this all friend families. Thus, after Timofey starts to feed crows under some tree, all the families that are friends to the family living on this tree, as well as their friends and so on, fly to the feeding place. Of course, the family living on the tree also comes to the feeding place.Today Timofey came to the alley and noticed that all the families that live on trees with numbers strictly less than l or strictly greater than r have flown away. Thus, it is not possible to pass the information about feeding through them. Moreover, there is no need to feed them. Help Timofey to learn what is the minimum number of trees under which he has to feed crows so that all the families that have remained will get the information about feeding. You are given several situations, described by integers l and r, you need to calculate the answer for all of them.InputThe first line contains integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 5), where n is the number of trees, and k is the maximum possible distance between friend families.The next line contains single integer m (0 ≤ m ≤ n·k) — the number of pair of friend families. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ 105), that means that the families on trees u and v are friends. It is guaranteed that u ≠ v and |u - v| ≤ k. All the given pairs are distinct.The next line contains single integer q (1 ≤ q ≤ 105) — the number of situations you need to calculate the answer in.Each of the next q lines contains two integers l and r (1 ≤ l ≤ r ≤ 105), that means that in this situation families that have flown away lived on such trees x, so that either x < l or x > r.OutputPrint q lines. Line i should contain single integer — the answer in the i-th situation.ExampleInput5 331 32 34 551 11 22 31 31 5Output12112NoteIn the first example the following family pairs are friends: (1, 3), (2, 3) and (4, 5). In the first situation only the first family has remained, so the answer is 1. In the second situation the first two families have remained, and they aren't friends, so the answer is 2. In the third situation the families 2 and 3 are friends, so it is enough to feed any of them, the answer is 1. In the fourth situation we can feed the first family, then the third family will get the information from the first family, and the second family will get the information from the third. The answer is 1. In the fifth situation we can feed the first and the fifth families, so the answer is 2.
Input5 331 32 34 551 11 22 31 31 5
Output12112
7 seconds
256 megabytes
['data structures', 'divide and conquer', 'dsu', '*2900']
D. Timofey and a flat treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Timofey has a big tree — an undirected connected graph with n vertices and no simple cycles. He likes to walk along it. His tree is flat so when he walks along it he sees it entirely. Quite naturally, when he stands on a vertex, he sees the tree as a rooted tree with the root in this vertex.Timofey assumes that the more non-isomorphic subtrees are there in the tree, the more beautiful the tree is. A subtree of a vertex is a subgraph containing this vertex and all its descendants. You should tell Timofey the vertex in which he should stand to see the most beautiful rooted tree.Subtrees of vertices u and v are isomorphic if the number of children of u equals the number of children of v, and their children can be arranged in such a way that the subtree of the first son of u is isomorphic to the subtree of the first son of v, the subtree of the second son of u is isomorphic to the subtree of the second son of v, and so on. In particular, subtrees consisting of single vertex are isomorphic to each other.InputFirst line contains single integer n (1 ≤ n ≤ 105) — number of vertices in the tree.Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ 105, ui ≠ vi), denoting the vertices the i-th edge connects.It is guaranteed that the given graph is a tree.OutputPrint single integer — the index of the vertex in which Timofey should stand. If there are many answers, you can print any of them.ExamplesInput31 22 3Output1Input71 24 22 35 66 73 7Output1Input101 71 89 45 19 23 510 610 95 10Output2NoteIn the first example we can stand in the vertex 1 or in the vertex 3 so that every subtree is non-isomorphic. If we stand in the vertex 2, then subtrees of vertices 1 and 3 are isomorphic.In the second example, if we stand in the vertex 1, then only subtrees of vertices 4 and 5 are isomorphic.In the third example, if we stand in the vertex 1, then subtrees of vertices 2, 3, 4, 6, 7 and 8 are isomorphic. If we stand in the vertex 2, than only subtrees of vertices 3, 4, 6, 7 and 8 are isomorphic. If we stand in the vertex 5, then subtrees of vertices 2, 3, 4, 6, 7 and 8 are isomorphic, and subtrees of vertices 1 and 9 are isomorphic as well: 1 9 /\ /\7 8 4 2
Input31 22 3
Output1
4 seconds
256 megabytes
['data structures', 'graphs', 'hashing', 'shortest paths', 'trees', '*2900']
C. Timofey and remodulingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)·d, each taken modulo m.InputThe first line contains two integers m and n (2 ≤ m ≤ 109 + 7, 1 ≤ n ≤ 105, m is prime) — Timofey's favorite prime module and the length of the sequence.The second line contains n distinct integers a1, a2, ..., an (0 ≤ ai < m) — the elements of the sequence.OutputPrint -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.Otherwise, print two integers — the first element of the obtained progression x (0 ≤ x < m) and its difference d (0 ≤ d < m).If there are multiple answers, print any of them.ExamplesInput17 50 2 4 13 15Output13 2Input17 50 2 4 13 14Output-1Input5 31 2 3Output3 4
Input17 50 2 4 13 15
Output13 2
2 seconds
256 megabytes
['brute force', 'implementation', 'math', 'number theory', '*2600']
B. Timofey and rectanglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length The picture corresponds to the first example InputThe first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109,  - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.OutputPrint "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.ExampleInput80 0 5 32 -1 5 0-3 -4 2 -1-1 -1 2 0-3 0 0 55 2 10 37 -3 10 24 -2 7 -1OutputYES12232241
Input80 0 5 32 -1 5 0-3 -4 2 -1-1 -1 2 0-3 0 0 55 2 10 37 -3 10 24 -2 7 -1
OutputYES12232241
2 seconds
256 megabytes
['constructive algorithms', 'geometry', '*2100']
A. Timofey and a treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.InputThe first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.OutputPrint "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.ExamplesInput41 22 33 41 2 1 1OutputYES2Input31 22 31 2 3OutputYES2Input41 22 33 41 2 1 2OutputNO
Input41 22 33 41 2 1 1
OutputYES2
2 seconds
256 megabytes
['dfs and similar', 'dp', 'dsu', 'graphs', 'implementation', 'trees', '*1600']
F. Tree nestingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two trees (connected undirected acyclic graphs) S and T.Count the number of subtrees (connected subgraphs) of S that are isomorphic to tree T. Since this number can get quite large, output it modulo 109 + 7.Two subtrees of tree S are considered different, if there exists a vertex in S that belongs to exactly one of them.Tree G is called isomorphic to tree H if there exists a bijection f from the set of vertices of G to the set of vertices of H that has the following property: if there is an edge between vertices A and B in tree G, then there must be an edge between vertices f(A) and f(B) in tree H. And vice versa — if there is an edge between vertices A and B in tree H, there must be an edge between f - 1(A) and f - 1(B) in tree G.InputThe first line contains a single integer |S| (1 ≤ |S| ≤ 1000) — the number of vertices of tree S.Next |S| - 1 lines contain two integers ui and vi (1 ≤ ui, vi ≤ |S|) and describe edges of tree S.The next line contains a single integer |T| (1 ≤ |T| ≤ 12) — the number of vertices of tree T.Next |T| - 1 lines contain two integers xi and yi (1 ≤ xi, yi ≤ |T|) and describe edges of tree T.OutputOn the first line output a single integer — the answer to the given task modulo 109 + 7.ExamplesInput51 22 33 44 531 22 3Output3Input32 33 131 21 3Output1Input71 21 31 41 51 61 744 14 24 3Output20Input51 22 33 44 544 14 24 3Output0
Input51 22 33 44 531 22 3
Output3
2 seconds
256 megabytes
['combinatorics', 'graphs', 'trees', '*2800']
E. Radio stationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the lattice points of the coordinate line there are n radio stations, the i-th of which is described by three integers: xi — the coordinate of the i-th station on the line, ri — the broadcasting range of the i-th station, fi — the broadcasting frequency of the i-th station. We will say that two radio stations with numbers i and j reach each other, if the broadcasting range of each of them is more or equal to the distance between them. In other words min(ri, rj) ≥ |xi - xj|.Let's call a pair of radio stations (i, j) bad if i < j, stations i and j reach each other and they are close in frequency, that is, |fi - fj| ≤ k.Find the number of bad pairs of radio stations.InputThe first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 10) — the number of radio stations and the maximum difference in the frequencies for the pair of stations that reach each other to be considered bad.In the next n lines follow the descriptions of radio stations. Each line contains three integers xi, ri and fi (1 ≤ xi, ri ≤ 109, 1 ≤ fi ≤ 104) — the coordinate of the i-th radio station, it's broadcasting range and it's broadcasting frequency. No two radio stations will share a coordinate.OutputOutput the number of bad pairs of radio stations.ExamplesInput3 21 3 103 2 54 10 8Output1Input3 31 3 103 2 54 10 8Output2Input5 11 3 22 2 43 2 14 2 15 3 3Output2Input5 11 5 22 5 43 5 14 5 15 5 3Output5
Input3 21 3 103 2 54 10 8
Output1
2 seconds
256 megabytes
['binary search', 'data structures', '*2200']
D. Maximum pathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular table 3 × n. Each cell contains an integer. You can move from one cell to another if they share a side.Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.InputThe first line contains an integer n (1 ≤ n ≤ 105)  — the number of columns in the table.Next three lines contain n integers each  — the description of the table. The j-th number in the i-th line corresponds to the cell aij ( - 109 ≤ aij ≤ 109) of the table.OutputOutput the maximum sum of numbers on a path from the upper left cell to the bottom right cell of the table, that doesn't visit any of the cells twice.ExamplesInput31 1 11 -1 11 1 1Output7Input510 10 10 -1 -1-1 10 10 10 10-1 10 10 10 10Output110NoteThe path for the first example: The path for the second example:
Input31 1 11 -1 11 1 1
Output7
1 second
256 megabytes
['dp', 'greedy', 'implementation', '*2300']
C. Two stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.InputThe first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.OutputOn the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.If the answer consists of zero characters, output «-» (a minus sign).ExamplesInputhibobOutput-InputabcaacceptedOutputacInputabacabaabcdcbaOutputabcbaNoteIn the first example strings a and b don't share any symbols, so the longest string that you can get is empty.In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Inputhibob
Output-
2 seconds
256 megabytes
['binary search', 'hashing', 'strings', 'two pointers', '*2100']
B. USB vs. PS/2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDue to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.InputThe first line contains three integers a, b and c (0 ≤ a, b, c ≤ 105)  — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively.The next line contains one integer m (0 ≤ m ≤ 3·105)  — the number of mouses in the price list.The next m lines each describe another mouse. The i-th line contains first integer vali (1 ≤ vali ≤ 109)  — the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.OutputOutput two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.ExampleInput2 1 145 USB6 PS/23 PS/27 PS/2Output3 14NoteIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.
Input2 1 145 USB6 PS/23 PS/27 PS/2
Output3 14
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', 'two pointers', '*1400']
A. k-th divisortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist.Divisor of n is any such natural number, that n can be divided by it without remainder.InputThe first line contains two integers n and k (1 ≤ n ≤ 1015, 1 ≤ k ≤ 109).OutputIf n has less than k divisors, output -1.Otherwise, output the k-th smallest divisor of n.ExamplesInput4 2Output2Input5 3Output-1Input12 5Output6NoteIn the first example, number 4 has three divisors: 1, 2 and 4. The second one is 2.In the second example, number 5 has only two divisors: 1 and 5. The third divisor doesn't exist, so the answer is -1.
Input4 2
Output2
2 seconds
256 megabytes
['math', 'number theory', '*1400']
F. Dasha and Photostime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDasha decided to have a rest after solving the problem D and began to look photos from previous competitions.Let's call photos as the matrix with the size n × m, which consists of lowercase English letters.Some k photos especially interested her, because they can be received from photo-template by painting a rectangular area in a certain color. Let's call such photos special. More formally the i-th special photo is received from the photo-template by replacing all characters on some rectangle with upper left corner of the cell with coordinates (ai, bi) and lower right corner in the cell with coordinates (ci, di) to the symbol ei.Dasha asks you to find the special photo so that the total distance from it to all other special photos is minimum. And calculate this distance.Determine the distance between two photos as the sum of distances between all corresponding letters. The distance between two letters is the difference module of their positions in the alphabet. For example, the distance between letters 'h' and 'm' equals |8 - 13| = 5, because the letter 'h' is the 8-th in the alphabet, the letter 'm' is the 13-th.InputThe first line contains three integers n, m, k (1 ≤ n, m ≤ 103, 1 ≤ k ≤ 3·105) — the number of strings in the photo-template, the number of columns and the number of special photos which are interesting for Dasha. The next n lines contains the string with m length which consists of little Latin characters — the description of the photo-template.Each of the next k lines contains the description of the special photo in the following format, "ai bi ci di ei" (1 ≤ ai ≤ ci ≤ n, 1 ≤ bi ≤ di ≤ m), where (ai, bi) — is the coordinate of the upper left corner of the rectangle, (ci, di) — is the description of the lower right corner, and ei — is the little Latin letter which replaces the photo-template in the described rectangle. OutputIn the only line print the minimum total distance from the found special photo to all other special photos.ExamplesInput3 3 2aaaaaaaaa1 1 2 2 b2 2 3 3 cOutput10Input5 5 3abcdeeabcddeabccdeabbcdea1 1 3 4 f1 2 3 3 e1 3 3 4 iOutput59NoteIn the first example the photos are following: bba aaabba accaaa accThe distance between them is 10.
Input3 3 2aaaaaaaaa1 1 2 2 b2 2 3 3 c
Output10
4 seconds
512 megabytes
['brute force', 'data structures', 'dp', 'implementation', '*2600']
E. Dasha and Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices.The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane.It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value.InputThe first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi.It is guaranteed that the described graph is a tree.OutputIf the puzzle doesn't have a solution then in the only line print "NO".Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree.If there are several solutions, print any of them. ExamplesInput71 21 32 42 53 63 7OutputYES0 01 00 12 01 -1-1 10 2Input61 22 32 42 52 6OutputNOInput41 22 33 4OutputYES3 34 35 36 3NoteIn the first sample one of the possible positions of tree is:
Input71 21 32 42 53 63 7
OutputYES0 01 00 12 01 -1-1 10 2
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'trees', '*2000']
D. Dasha and Very Difficult Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDasha logged into the system and began to solve problems. One of them is as follows:Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l ≤ ai ≤ r and l ≤ bi ≤ r. About sequence c we know that all its elements are distinct. Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.InputThe first line contains three integers n, l, r (1 ≤ n ≤ 105, 1 ≤ l ≤ r ≤ 109) — the length of the sequence and boundaries of the segment where the elements of sequences a and b are.The next line contains n integers a1,  a2,  ...,  an (l ≤ ai ≤ r) — the elements of the sequence a.The next line contains n distinct integers p1,  p2,  ...,  pn (1 ≤ pi ≤ n) — the compressed sequence of the sequence c.OutputIf there is no the suitable sequence b, then in the only line print "-1".Otherwise, in the only line print n integers — the elements of any suitable sequence b.ExamplesInput5 1 51 1 1 1 13 1 5 4 2Output3 1 5 4 2 Input4 2 93 4 8 93 2 1 4Output2 2 2 9 Input6 1 51 1 1 1 1 12 3 5 4 1 6Output-1NoteSequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1,  - 2,  - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Input5 1 51 1 1 1 13 1 5 4 2
Output3 1 5 4 2
2 seconds
256 megabytes
['binary search', 'brute force', 'constructive algorithms', 'greedy', 'sortings', '*1700']
C. Dasha and Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: There is at least one digit in the string, There is at least one lowercase (small) letter of the Latin alphabet in the string, There is at least one of three listed symbols in the string: '#', '*', '&'. Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. InputThe first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.You have such input data that you can always get a valid password.OutputPrint one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. ExamplesInput3 41**2a3*0c4**Output1Input5 5#*&#**a1c&&q2w*#a3c#*&#*&Output3NoteIn the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. In the second test one of possible algorithms will be: to move the pointer of the second symbol once to the right. to move the pointer of the third symbol twice to the right.
Input3 41**2a3*0c4**
Output1
2 seconds
256 megabytes
['brute force', 'dp', 'implementation', '*1500']
B. Dasha and friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRunning with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation:The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you look on him from above. All barriers are located at integer distance from each other along the track. Her friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the n barriers. Thus, each of them wrote n integers in the ascending order, each of them was between 0 and L - 1, inclusively. Consider an example. Let L = 8, blue points are barriers, and green points are Kefa's start (A) and Sasha's start (B). Then Kefa writes down the sequence [2, 4, 6], and Sasha writes down [1, 5, 7]. There are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks. Write the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction — counterclockwise, if you look on a track from above. InputThe first line contains two integers n and L (1 ≤ n ≤ 50, n ≤ L ≤ 100) — the number of barriers on a track and its length. The second line contains n distinct integers in the ascending order — the distance from Kefa's start to each barrier in the order of its appearance. All integers are in the range from 0 to L - 1 inclusively.The second line contains n distinct integers in the ascending order — the distance from Sasha's start to each barrier in the order of its overcoming. All integers are in the range from 0 to L - 1 inclusively.OutputPrint "YES" (without quotes), if Kefa and Sasha ran the coinciding tracks (it means that the position of all barriers coincides, if they start running from the same points on the track). Otherwise print "NO" (without quotes).ExamplesInput3 82 4 61 5 7OutputYESInput4 92 3 5 80 1 3 6OutputYESInput2 41 31 2OutputNONoteThe first test is analyzed in the statement.
Input3 82 4 61 5 7
OutputYES
2 seconds
256 megabytes
['brute force', 'implementation', 'math', '*1300']
A. Dasha and Stairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn her way to programming school tiger Dasha faced her first test — a huge staircase! The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers. You need to check whether there is an interval of steps from the l-th to the r-th (1 ≤ l ≤ r), for which values that Dasha has found are correct.InputIn the only line you are given two integers a, b (0 ≤ a, b ≤ 100) — the number of even and odd steps, accordingly.OutputIn the only line print "YES", if the interval of steps described above exists, and "NO" otherwise.ExamplesInput2 3OutputYESInput3 1OutputNONoteIn the first example one of suitable intervals is from 1 to 5. The interval contains two even steps — 2 and 4, and three odd: 1, 3 and 5.
Input2 3
OutputYES
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', 'math', '*1000']
B. Frodo and pillowstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have. Frodo will sleep on the k-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?InputThe only line contain three integers n, m and k (1 ≤ n ≤ m ≤ 109, 1 ≤ k ≤ n) — the number of hobbits, the number of pillows and the number of Frodo's bed.OutputPrint single integer — the maximum number of pillows Frodo can have so that no one is hurt.ExamplesInput4 6 2Output2Input3 10 3Output4Input3 6 1Output3NoteIn the first example Frodo can have at most two pillows. In this case, he can give two pillows to the hobbit on the first bed, and one pillow to each of the hobbits on the third and the fourth beds.In the second example Frodo can take at most four pillows, giving three pillows to each of the others.In the third example Frodo can take three pillows, giving two pillows to the hobbit in the middle and one pillow to the hobbit on the third bed.
Input4 6 2
Output2
1 second
256 megabytes
['binary search', 'greedy', '*1500']
A. Petr and a calendartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.InputThe only line contain two integers m and d (1 ≤ m ≤ 12, 1 ≤ d ≤ 7) — the number of month (January is the first month, December is the twelfth) and the weekday of the first date of this month (1 is Monday, 7 is Sunday).OutputPrint single integer: the number of columns the table should have.ExamplesInput1 7Output6Input1 1Output5Input11 6Output5NoteThe first example corresponds to the January 2017 shown on the picture in the statements.In the second example 1-st January is Monday, so the whole month fits into 5 columns.In the third example 1-st November is Saturday and 5 columns is enough.
Input1 7
Output6
2 seconds
256 megabytes
['implementation', 'math', '*800']
F. Geometrical Progressiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l ≤ ai ≤ r and ai ≠ aj , where a1, a2, ..., an is the geometrical progression, 1 ≤ i, j ≤ n and i ≠ j.Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is .Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 ≤ i ≤ n) that ai ≠ bi.InputThe first and the only line cotains three integers n, l and r (1 ≤ n ≤ 107, 1 ≤ l ≤ r ≤ 107).OutputPrint the integer K — is the answer to the problem.ExamplesInput1 1 10Output10Input2 6 9Output12Input3 1 10Output8Input3 3 10Output2NoteThese are possible progressions for the first test of examples: 1; 2; 3; 4; 5; 6; 7; 8; 9; 10. These are possible progressions for the second test of examples: 6, 7; 6, 8; 6, 9; 7, 6; 7, 8; 7, 9; 8, 6; 8, 7; 8, 9; 9, 6; 9, 7; 9, 8. These are possible progressions for the third test of examples: 1, 2, 4; 1, 3, 9; 2, 4, 8; 4, 2, 1; 4, 6, 9; 8, 4, 2; 9, 3, 1; 9, 6, 4. These are possible progressions for the fourth test of examples: 4, 6, 9; 9, 6, 4.
Input1 1 10
Output10
4 seconds
256 megabytes
['brute force', 'math', 'number theory', '*2400']
E. Broken Treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree that has n vertices, which are numbered from 1 to n, where the vertex number one is the root. Each edge has weight wi and strength pi.Botanist Innokentiy, who is the only member of the jury of the Olympiad in Informatics, doesn't like broken trees. The tree is broken if there is such an edge the strength of which is less than the sum of weight of subtree's edges to which it leads.It is allowed to reduce weight of any edge by arbitrary integer value, but then the strength of its edge is reduced by the same value. It means if the weight of the edge is 10, and the strength is 12, then by the reducing the weight by 7 its weight will equal 3, and the strength will equal 5. It is not allowed to increase the weight of the edge.Your task is to get the tree, which is not broken, by reducing the weight of edges of the given tree, and also all edged should have the positive weight, moreover, the total weight of all edges should be as large as possible.It is obvious that the strength of edges can not be negative, however it can equal zero if the weight of the subtree equals zero. InputThe first line contains the integer n (1 ≤ n ≤ 2·105) — the number of vertices in the tree. The next n - 1 lines contains the description of edges. Each line contains four integers x, y, w, p (1 ≤ x, y ≤ n, 1 ≤ w ≤ 109, 0 ≤ p ≤ 109), where x and y — vertices which connect the edge (the vertex number x is the parent of the vertex number y), w and p are the weight and the strength of the edge, accordingly. It is guaranteed that the edges describe the tree with the root in the vertex 1.OutputIf it is impossible to get unbroken tree from the given tree, print -1 in the only line.Otherwise, the output data should contain n lines:In the first line print the number n — the number of vertices on the tree. In the next n - 1 lines print the description of edges of the resulting tree. Each line should contain four integers x, y, w, p (1 ≤ x, y ≤ n, 1 ≤ w ≤ 109, 0 ≤ p ≤ 109), where x and y — vertices, which the edge connects (the vertex number x is the parent of the vertex number y), w and p are the new weight and the strength of the edge, accordingly. Print edges in the same order as they are given in input data: the first two integers of each line should not be changed. ExamplesInput31 3 5 73 2 4 3Output31 3 5 73 2 4 3Input41 3 2 33 4 5 13 2 3 3Output-1Input51 2 2 42 4 1 94 5 5 64 3 4 8Output51 2 2 42 4 1 94 5 1 24 3 2 6Input71 2 5 22 3 4 31 4 3 74 5 4 14 6 3 26 7 1 6Output71 2 5 22 3 2 11 4 3 74 5 3 04 6 3 26 7 1 6
Input31 3 5 73 2 4 3
Output31 3 5 73 2 4 3
4 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'greedy', 'trees', '*2600']
D. Ability To Converttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets 11311 (475 = 1·162 + 13·161 + 11·160). Alexander lived calmly until he tried to convert the number back to the decimal number system.Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base n he will get the number k.InputThe first line contains the integer n (2 ≤ n ≤ 109). The second line contains the integer k (0 ≤ k < 1060), it is guaranteed that the number k contains no more than 60 symbols. All digits in the second line are strictly less than n.Alexander guarantees that the answer exists and does not exceed 1018.The number k doesn't contain leading zeros.OutputPrint the number x (0 ≤ x ≤ 1018) — the answer to the problem.ExamplesInput1312Output12Input1611311Output475Input20999Output3789Input172016Output594NoteIn the first example 12 could be obtained by converting two numbers to the system with base 13: 12 = 12·130 or 15 = 1·131 + 2·130.
Input1312
Output12
1 second
256 megabytes
['constructive algorithms', 'dp', 'greedy', 'math', 'strings', '*2000']
C. Unfair Polltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others.Seating in the class looks like a rectangle, where n rows with m pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the 1-st row, the 2-nd row, ..., the n - 1-st row, the n-th row, the n - 1-st row, ..., the 2-nd row, the 1-st row, the 2-nd row, ...The order of asking of pupils on the same row is always the same: the 1-st pupil, the 2-nd pupil, ..., the m-th pupil.During the lesson the teacher managed to ask exactly k questions from pupils in order described above. Sergei seats on the x-th row, on the y-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values: the maximum number of questions a particular pupil is asked, the minimum number of questions a particular pupil is asked, how many times the teacher asked Sergei. If there is only one row in the class, then the teacher always asks children from this row.InputThe first and the only line contains five integers n, m, k, x and y (1 ≤ n, m ≤ 100, 1 ≤ k ≤ 1018, 1 ≤ x ≤ n, 1 ≤ y ≤ m).OutputPrint three integers: the maximum number of questions a particular pupil is asked, the minimum number of questions a particular pupil is asked, how many times the teacher asked Sergei. ExamplesInput1 3 8 1 1Output3 2 3Input4 2 9 4 2Output2 1 1Input5 5 25 4 3Output1 1 1Input100 100 1000000000000000000 100 100Output101010101010101 50505050505051 50505050505051NoteThe order of asking pupils in the first test: the pupil from the first row who seats at the first table, it means it is Sergei; the pupil from the first row who seats at the second table; the pupil from the first row who seats at the third table; the pupil from the first row who seats at the first table, it means it is Sergei; the pupil from the first row who seats at the second table; the pupil from the first row who seats at the third table; the pupil from the first row who seats at the first table, it means it is Sergei; the pupil from the first row who seats at the second table; The order of asking pupils in the second test: the pupil from the first row who seats at the first table; the pupil from the first row who seats at the second table; the pupil from the second row who seats at the first table; the pupil from the second row who seats at the second table; the pupil from the third row who seats at the first table; the pupil from the third row who seats at the second table; the pupil from the fourth row who seats at the first table; the pupil from the fourth row who seats at the second table, it means it is Sergei; the pupil from the third row who seats at the first table;
Input1 3 8 1 1
Output3 2 3
1 second
256 megabytes
['binary search', 'constructive algorithms', 'implementation', 'math', '*1700']
B. Blown Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' — red, 'B' — blue, 'Y' — yellow, 'G' — green.Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.InputThe first and the only line contains the string s (4 ≤ |s| ≤ 100), which describes the garland, the i-th symbol of which describes the color of the i-th light bulb in the order from the beginning of garland: 'R' — the light bulb is red, 'B' — the light bulb is blue, 'Y' — the light bulb is yellow, 'G' — the light bulb is green, '!' — the light bulb is dead. The string s can not contain other symbols except those five which were described. It is guaranteed that in the given string at least once there is each of four letters 'R', 'B', 'Y' and 'G'. It is guaranteed that the string s is correct garland with some blown light bulbs, it means that for example the line "GRBY!!!B" can not be in the input data. OutputIn the only line print four integers kr, kb, ky, kg — the number of dead light bulbs of red, blue, yellow and green colors accordingly.ExamplesInputRYBGRYBGROutput0 0 0 0Input!RGYBOutput0 1 0 0Input!!!!YGRBOutput1 1 1 1Input!GB!RG!Y!Output2 1 1 0NoteIn the first example there are no dead light bulbs.In the second example it is obvious that one blue bulb is blown, because it could not be light bulbs of other colors on its place according to the statements.
InputRYBGRYBGR
Output0 0 0 0
1 second
256 megabytes
['brute force', 'implementation', 'number theory', '*1100']
A. Holiday Of Equalitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them. InputThe first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom.The second line contains n integers a1, a2, ..., an, where ai (0 ≤ ai ≤ 106) — the welfare of the i-th citizen.OutputIn the only line print the integer S — the minimum number of burles which are had to spend.ExamplesInput50 1 2 3 4Output10Input51 1 0 1 1Output1Input31 3 1Output4Input112Output0NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.
Input50 1 2 3 4
Output10
1 second
256 megabytes
['implementation', 'math', '*800']
G. Can Bash Save the Day?time limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputWhoa! You did a great job helping Team Rocket who managed to capture all the Pokemons sent by Bash. Meowth, part of Team Rocket, having already mastered the human language, now wants to become a master in programming as well. He agrees to free the Pokemons if Bash can answer his questions.Initially, Meowth gives Bash a weighted tree containing n nodes and a sequence a1, a2..., an which is a permutation of 1, 2, ..., n. Now, Mewoth makes q queries of one of the following forms: 1 l r v: meaning Bash should report , where dist(a, b) is the length of the shortest path from node a to node b in the given tree. 2 x: meaning Bash should swap ax and ax + 1 in the given sequence. This new sequence is used for later queries. Help Bash to answer the questions!InputThe first line contains two integers n and q (1 ≤ n ≤ 2·105, 1 ≤ q ≤ 2·105) — the number of nodes in the tree and the number of queries, respectively.The next line contains n space-separated integers — the sequence a1, a2, ..., an which is a permutation of 1, 2, ..., n.Each of the next n - 1 lines contain three space-separated integers u, v, and w denoting that there exists an undirected edge between node u and node v of weight w, (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 106). It is guaranteed that the given graph is a tree.Each query consists of two lines. First line contains single integer t, indicating the type of the query. Next line contains the description of the query: t = 1: Second line contains three integers a, b and c (1 ≤ a, b, c < 230) using which l, r and v can be generated using the formula given below: , , . t = 2: Second line contains single integer a (1 ≤ a < 230) using which x can be generated using the formula given below: . The ansi is the answer for the i-th query, assume that ans0 = 0. If the i-th query is of type 2 then ansi = ansi - 1. It is guaranteed that: for each query of type 1: 1 ≤ l ≤ r ≤ n, 1 ≤ v ≤ n, for each query of type 2: 1 ≤ x ≤ n - 1. The operation means bitwise exclusive OR.OutputFor each query of type 1, output a single integer in a separate line, denoting the answer to the query.ExampleInput5 54 5 1 3 24 2 41 3 94 1 44 5 211 5 4122 20 20238239136 38 38Output233728NoteIn the sample, the actual queries are the following: 1 1 5 4 1 1 3 3 2 3 2 2 1 1 3 3
Input5 54 5 1 3 24 2 41 3 94 1 44 5 211 5 4122 20 20238239136 38 38
Output233728
5 seconds
768 megabytes
['data structures', 'divide and conquer', 'graphs', 'trees', '*3400']
F. Team Rocket Rises Againtime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city.InputThe first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in.Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters.It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities.OutputPrint a single integer, the answer to the problem.ExamplesInput4 4 31 2 12 3 12 4 13 1 1Output2Input7 11 21 2 51 3 52 4 22 5 23 6 33 7 34 6 23 4 26 7 34 5 74 7 7Output4NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2.
Input4 4 31 2 12 3 12 4 13 1 1
Output2
2.5 seconds
512 megabytes
['data structures', 'graphs', 'shortest paths', '*2800']
E. Bash Plays with Functionstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions.Bash defines a function f0(n), which denotes the number of ways of factoring n into two factors p and q such that gcd(p, q) = 1. In other words, f0(n) is the number of ordered pairs of positive integers (p, q) such that p·q = n and gcd(p, q) = 1.But Bash felt that it was too easy to calculate this function. So he defined a series of functions, where fr + 1 is defined as:Where (u, v) is any ordered pair of positive integers, they need not to be co-prime.Now Bash wants to know the value of fr(n) for different r and n. Since the value could be huge, he would like to know the value modulo 109 + 7. Help him!InputThe first line contains an integer q (1 ≤ q ≤ 106) — the number of values Bash wants to know.Each of the next q lines contain two integers r and n (0 ≤ r ≤ 106, 1 ≤ n ≤ 106), which denote Bash wants to know the value fr(n).OutputPrint q integers. For each pair of r and n given, print fr(n) modulo 109 + 7 on a separate line.ExampleInput50 301 253 652 54 48Output85254630
Input50 301 253 652 54 48
Output85254630
3 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'number theory', '*2500']
D. Felicity's Big Secret Revealedtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe gym leaders were fascinated by the evolutions which took place at Felicity camp. So, they were curious to know about the secret behind evolving Pokemon. The organizers of the camp gave the gym leaders a PokeBlock, a sequence of n ingredients. Each ingredient can be of type 0 or 1. Now the organizers told the gym leaders that to evolve a Pokemon of type k (k ≥ 2), they need to make a valid set of k cuts on the PokeBlock to get smaller blocks.Suppose the given PokeBlock sequence is b0b1b2... bn - 1. You have a choice of making cuts at n + 1 places, i.e., Before b0, between b0 and b1, between b1 and b2, ..., between bn - 2 and bn - 1, and after bn - 1.The n + 1 choices of making cuts are as follows (where a | denotes a possible cut):| b0 | b1 | b2 | ... | bn - 2 | bn - 1 |Consider a sequence of k cuts. Now each pair of consecutive cuts will contain a binary string between them, formed from the ingredient types. The ingredients before the first cut and after the last cut are wasted, which is to say they are not considered. So there will be exactly k - 1 such binary substrings. Every substring can be read as a binary number. Let m be the maximum number out of the obtained numbers. If all the obtained numbers are positive and the set of the obtained numbers contains all integers from 1 to m, then this set of cuts is said to be a valid set of cuts.For example, suppose the given PokeBlock sequence is 101101001110 and we made 5 cuts in the following way:10 | 11 | 010 | 01 | 1 | 10So the 4 binary substrings obtained are: 11, 010, 01 and 1, which correspond to the numbers 3, 2, 1 and 1 respectively. Here m = 3, as it is the maximum value among the obtained numbers. And all the obtained numbers are positive and we have obtained all integers from 1 to m. Hence this set of cuts is a valid set of 5 cuts.A Pokemon of type k will evolve only if the PokeBlock is cut using a valid set of k cuts. There can be many valid sets of the same size. Two valid sets of k cuts are considered different if there is a cut in one set which is not there in the other set.Let f(k) denote the number of valid sets of k cuts. Find the value of . Since the value of s can be very large, output s modulo 109 + 7.InputThe input consists of two lines. The first line consists an integer n (1 ≤ n ≤ 75) — the length of the PokeBlock. The next line contains the PokeBlock, a binary string of length n.OutputOutput a single integer, containing the answer to the problem, i.e., the value of s modulo 109 + 7.ExamplesInput41011Output10Input210Output1NoteIn the first sample, the sets of valid cuts are:Size 2: |1|011, 1|01|1, 10|1|1, 101|1|.Size 3: |1|01|1, |10|1|1, 10|1|1|, 1|01|1|.Size 4: |10|1|1|, |1|01|1|.Hence, f(2) = 4, f(3) = 4 and f(4) = 2. So, the value of s = 10.In the second sample, the set of valid cuts is:Size 2: |1|0.Hence, f(2) = 1 and f(3) = 0. So, the value of s = 1.
Input41011
Output10
4 seconds
512 megabytes
['bitmasks', 'dp', '*2200']
C. Felicity is Coming!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has gi Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation f of {1, 2, ..., m}, such that f(x) = y means that a Pokemon of type x evolves into a Pokemon of type y.The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol.Two evolution plans f1 and f2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f1(i) ≠ f2(i).Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109 + 7.InputThe first line contains two integers n and m (1 ≤ n ≤ 105, 1 ≤ m ≤ 106) — the number of gyms and the number of Pokemon types.The next n lines contain the description of Pokemons in the gyms. The i-th of these lines begins with the integer gi (1 ≤ gi ≤ 105) — the number of Pokemon in the i-th gym. After that gi integers follow, denoting types of the Pokemons in the i-th gym. Each of these integers is between 1 and m.The total number of Pokemons (the sum of all gi) does not exceed 5·105.OutputOutput the number of valid evolution plans modulo 109 + 7.ExamplesInput2 32 1 22 2 3Output1Input1 33 1 2 3Output6Input2 42 1 23 2 3 4Output2Input2 23 2 2 12 1 2Output1Input3 72 1 22 3 43 5 6 7Output24NoteIn the first case, the only possible evolution plan is: In the second case, any permutation of (1,  2,  3) is valid.In the third case, there are two possible plans: In the fourth case, the only possible evolution plan is:
Input2 32 1 22 2 3
Output1
2 seconds
256 megabytes
['data structures', 'hashing', 'sortings', 'strings', '*1900']
B. Bash's Big Daytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.InputThe input consists of two lines.The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab.The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.OutputPrint single integer — the maximum number of Pokemons Bash can take.ExamplesInput32 3 4Output2Input52 3 4 6 7Output3Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Input32 3 4
Output2
2 seconds
512 megabytes
['greedy', 'math', 'number theory', '*1400']
A. Gotta Catch Em' All!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper.Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?Note: uppercase and lowercase letters are considered different.InputInput contains a single line containing a string s (1  ≤  |s|  ≤  105) — the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s.The string s contains lowercase and uppercase English letters, i.e. .OutputOutput a single integer, the answer to the problem.ExamplesInputBulbbasaurOutput1InputFOutput0InputaBddulbasaurrgndgbualdBdsagaurrgndbbOutput2NoteIn the first case, you could pick: Bulbbasaur.In the second case, there is no way to pick even a single Bulbasaur.In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words "Bulbasaur".
InputBulbbasaur
Output1
1 second
256 megabytes
['implementation', '*1000']
F. Long numbertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider the following grammar: <expression> ::= <term> | <expression> '+' <term> <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')' <number> ::= <pos_digit> | <number> <digit> <digit> ::= '0' | <pos_digit> <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'This grammar describes a number in decimal system using the following rules: <number> describes itself, <number>-<number> (l-r, l ≤ r) describes integer which is concatenation of all integers from l to r, written without leading zeros. For example, 8-11 describes 891011, <number>(<expression>) describes integer which is concatenation of <number> copies of integer described by <expression>, <expression>+<term> describes integer which is concatenation of integers described by <expression> and <term>.For example, 2(2-4+1)+2(2(17)) describes the integer 2341234117171717.You are given an expression in the given grammar. Print the integer described by it modulo 109 + 7.InputThe only line contains a non-empty string at most 105 characters long which is valid according to the given grammar. In particular, it means that in terms l-r l ≤ r holds.OutputPrint single integer — the number described by the expression modulo 109 + 7.ExamplesInput8-11Output891011Input2(2-4+1)+2(2(17))Output100783079Input1234-5678Output745428774Input1+2+3+4-5+6+7-9Output123456789
Input8-11
Output891011
2 seconds
512 megabytes
['expression parsing', 'math', 'number theory', '*3400']
E. Byteland coinstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n types of coins in Byteland. Conveniently, the denomination of the coin type k divides the denomination of the coin type k + 1, the denomination of the coin type 1 equals 1 tugrick. The ratio of the denominations of coin types k + 1 and k equals ak. It is known that for each x there are at most 20 coin types of denomination x.Byteasar has bk coins of type k with him, and he needs to pay exactly m tugricks. It is known that Byteasar never has more than 3·105 coins with him. Byteasar want to know how many ways there are to pay exactly m tugricks. Two ways are different if there is an integer k such that the amount of coins of type k differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo 109 + 7.InputThe first line contains single integer n (1 ≤ n ≤ 3·105) — the number of coin types.The second line contains n - 1 integers a1, a2, ..., an - 1 (1 ≤ ak ≤ 109) — the ratios between the coin types denominations. It is guaranteed that for each x there are at most 20 coin types of denomination x.The third line contains n non-negative integers b1, b2, ..., bn — the number of coins of each type Byteasar has. It is guaranteed that the sum of these integers doesn't exceed 3·105.The fourth line contains single integer m (0 ≤ m < 1010000) — the amount in tugricks Byteasar needs to pay.OutputPrint single integer — the number of ways to pay exactly m tugricks modulo 109 + 7.ExamplesInput142Output1Input214 42Output3Input33 310 10 1017Output6NoteIn the first example Byteasar has 4 coins of denomination 1, and he has to pay 2 tugricks. There is only one way.In the second example Byteasar has 4 coins of each of two different types of denomination 1, he has to pay 2 tugricks. There are 3 ways: pay one coin of the first type and one coin of the other, pay two coins of the first type, and pay two coins of the second type.In the third example the denominations are equal to 1, 3, 9.
Input142
Output1
1 second
512 megabytes
['combinatorics', 'dp', 'math', '*3200']
D. Bacterial Meleetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJulia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.InputThe first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000).The second line contains n small Latin letters that describe the initial population of the testtube.OutputPrint one number — the answer to the problem modulo 109 + 7.ExamplesInput3aaaOutput1Input2abOutput3Input4babbOutput11Input7abacabaOutput589NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Input3aaa
Output1
2 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'string suffix structures', '*2400']
C. Nikita and stacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer x on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing.Nikita made m operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the i-th step he remembers an operation he made pi-th. In other words, he remembers the operations in order of some permutation p1, p2, ..., pm. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!InputThe first line contains the integer m (1 ≤ m ≤ 105) — the number of operations Nikita made.The next m lines contain the operations Nikita remembers. The i-th line starts with two integers pi and ti (1 ≤ pi ≤ m, ti = 0 or ti = 1) — the index of operation he remembers on the step i, and the type of the operation. ti equals 0, if the operation is pop(), and 1, is the operation is push(x). If the operation is push(x), the line also contains the integer xi (1 ≤ xi ≤ 106) — the integer added to the stack.It is guaranteed that each integer from 1 to m is present exactly once among integers pi.OutputPrint m integers. The integer i should equal the number on the top of the stack after performing all the operations Nikita remembered on the steps from 1 to i. If the stack is empty after performing all these operations, print -1.ExamplesInput22 1 21 0Output22Input31 1 22 1 33 0Output232Input55 04 03 1 12 1 11 1 2Output-1-1-1-12NoteIn the first example, after Nikita remembers the operation on the first step, the operation push(2) is the only operation, so the answer is 2. After he remembers the operation pop() which was done before push(2), answer stays the same.In the second example, the operations are push(2), push(3) and pop(). Nikita remembers them in the order they were performed.In the third example Nikita remembers the operations in the reversed order.
Input22 1 21 0
Output22
2 seconds
256 megabytes
['data structures', '*2200']
B. Travel Cardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.The fare is constructed in the following manner. There are three types of tickets: a ticket for one trip costs 20 byteland rubles, a ticket for 90 minutes costs 50 byteland rubles, a ticket for one day (1440 minutes) costs 120 byteland rubles. Note that a ticket for x minutes activated at time t can be used for trips started in time range from t to t + x - 1, inclusive. Assume that all trips take exactly one minute.To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is a, and the total sum charged before is b. Then the system charges the passenger the sum a - b.You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip.InputThe first line of input contains integer number n (1 ≤ n ≤ 105) — the number of trips made by passenger.Each of the following n lines contains the time of trip ti (0 ≤ ti ≤ 109), measured in minutes from the time of starting the system. All ti are different, given in ascending order, i. e. ti + 1 > ti holds for all 1 ≤ i < n.OutputOutput n integers. For each trip, print the sum the passenger is charged after it.ExamplesInput3102030Output202010Input1013454660103115126150256516Output20201002000202010NoteIn the first example, the system works as follows: for the first and second trips it is cheaper to pay for two one-trip tickets, so each time 20 rubles is charged, after the third trip the system understands that it would be cheaper to buy a ticket for 90 minutes. This ticket costs 50 rubles, and the passenger had already paid 40 rubles, so it is necessary to charge 10 rubles only.
Input3102030
Output202010
2 seconds
256 megabytes
['binary search', 'dp', '*1600']
A. Pavel and barbecuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.Pavel has a plan: a permutation p and a sequence b1, b2, ..., bn, consisting of zeros and ones. Each second Pavel move skewer on position i to position pi, and if bi equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions.Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well.There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (k ≥ 2n), so that after k seconds each skewer visits each of the 2n placements.It can be shown that some suitable pair of permutation p and sequence b exists for any n.InputThe first line contain the integer n (1 ≤ n ≤ 2·105) — the number of skewers.The second line contains a sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation, according to which Pavel wants to move the skewers.The third line contains a sequence b1, b2, ..., bn consisting of zeros and ones, according to which Pavel wants to reverse the skewers.OutputPrint single integer — the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements.ExamplesInput44 3 2 10 1 1 1Output2Input32 3 10 0 0Output1NoteIn the first example Pavel can change the permutation to 4, 3, 1, 2.In the second example Pavel can change any element of b to 1.
Input44 3 2 10 1 1 1
Output2
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', '*1700']
G. PolandBall and Many Other Ballstime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolandBall is standing in a row with Many Other Balls. More precisely, there are exactly n Balls. Balls are proud of their home land — and they want to prove that it's strong.The Balls decided to start with selecting exactly m groups of Balls, each consisting either of single Ball or two neighboring Balls. Each Ball can join no more than one group.The Balls really want to impress their Enemies. They kindly asked you to calculate number of such divisions for all m where 1 ≤ m ≤ k. Output all these values modulo 998244353, the Enemies will be impressed anyway.InputThere are exactly two numbers n and k (1 ≤ n ≤ 109, 1 ≤ k < 215), denoting the number of Balls and the maximim number of groups, respectively.OutputYou should output a sequence of k values. The i-th of them should represent the sought number of divisions into exactly i groups, according to PolandBall's rules.ExamplesInput3 3Output5 5 1 Input1 1Output1 Input5 10Output9 25 25 9 1 0 0 0 0 0 NoteIn the first sample case we can divide Balls into groups as follows: {1}, {2}, {3}, {12}, {23}.{12}{3}, {1}{23}, {1}{2}, {1}{3}, {2}{3}.{1}{2}{3}.Therefore, output is: 5 5 1.
Input3 3
Output5 5 1
6 seconds
256 megabytes
['combinatorics', 'divide and conquer', 'dp', 'fft', 'math', 'number theory', '*3200']
F. PolandBall and Giftstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's Christmas time! PolandBall and his friends will be giving themselves gifts. There are n Balls overall. Each Ball has someone for whom he should bring a present according to some permutation p, pi ≠ i for all i.Unfortunately, Balls are quite clumsy. We know earlier that exactly k of them will forget to bring their gift. A Ball number i will get his present if the following two constraints will hold: Ball number i will bring the present he should give. Ball x such that px = i will bring his present. What is minimum and maximum possible number of kids who will not get their present if exactly k Balls will forget theirs?InputThe first line of input contains two integers n and k (2 ≤ n ≤ 106, 0 ≤ k ≤ n), representing the number of Balls and the number of Balls who will forget to bring their presents. The second line contains the permutation p of integers from 1 to n, where pi is the index of Ball who should get a gift from the i-th Ball. For all i, pi ≠ i holds.OutputYou should output two values — minimum and maximum possible number of Balls who will not get their presents, in that order.ExamplesInput5 23 4 1 5 2Output2 4Input10 12 3 4 5 6 7 8 9 10 1Output2 2NoteIn the first sample, if the third and the first balls will forget to bring their presents, they will be th only balls not getting a present. Thus the minimum answer is 2. However, if the first ans the second balls will forget to bring their presents, then only the fifth ball will get a present. So, the maximum answer is 4.
Input5 23 4 1 5 2
Output2 4
1.5 seconds
256 megabytes
['bitmasks', 'dp', 'greedy', '*2600']
E. PolandBall and White-Red graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolandBall has an undirected simple graph consisting of n vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red. Colorfulness of the graph is a value min(dr, dw), where dr is the diameter of the red subgraph and dw is the diameter of white subgraph. The diameter of a graph is a largest value d such that shortest path between some pair of vertices in it is equal to d. If the graph is not connected, we consider its diameter to be -1.PolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to k. Can you help him and find any graph which satisfies PolandBall's requests?InputThe only one input line contains two integers n and k (2 ≤ n ≤ 1000, 1 ≤ k ≤ 1000), representing graph's size and sought colorfulness.OutputIf it's impossible to find a suitable graph, print -1.Otherwise, you can output any graph which fulfills PolandBall's requirements. First, output m — the number of red edges in your graph. Then, you should output m lines, each containing two integers ai and bi, (1 ≤ ai, bi ≤ n, ai ≠ bi) which means that there is an undirected red edge between vertices ai and bi. Every red edge should be printed exactly once, you can print the edges and the vertices of every edge in arbitrary order.Remember that PolandBall's graph should remain simple, so no loops or multiple edges are allowed.ExamplesInput4 1Output-1Input5 2Output41 22 33 44 5NoteIn the first sample case, no graph can fulfill PolandBall's requirements.In the second sample case, red graph is a path from 1 to 5. Its diameter is 4. However, white graph has diameter 2, because it consists of edges 1-3, 1-4, 1-5, 2-4, 2-5, 3-5.
Input4 1
Output-1
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'shortest paths', '*2400']
D. PolandBall and Polygontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex.Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.InputThere are only two numbers in the input: n and k (5 ≤ n ≤ 106, 2 ≤ k ≤ n - 2, gcd(n, k) = 1).OutputYou should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.ExamplesInput5 2Output2 3 5 8 11 Input10 3Output2 3 4 6 9 12 16 21 26 31 NoteThe greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines.
Input5 2
Output2 3 5 8 11
4 seconds
256 megabytes
['data structures', '*2000']
C. PolandBall and Foresttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?InputThe first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.It's guaranteed that the sequence p corresponds to some valid forest.Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:5 31 23 44 5OutputYou should output the number of trees in the forest where PolandBall lives.InteractionFrom the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.ExamplesInput52 1 5 3 3Output2Input11Output1NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Input52 1 5 3 3
Output2
1 second
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'interactive', 'trees', '*1300']
B. PolandBall and Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?InputThe first input line contains two integers n and m (1 ≤ n, m ≤ 103) — number of words PolandBall and EnemyBall know, respectively.Then n strings follow, one per line — words familiar to PolandBall.Then m strings follow, one per line — words familiar to EnemyBall.Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players.Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.OutputIn a single line of print the answer — "YES" if PolandBall wins and "NO" otherwise. Both Balls play optimally.ExamplesInput5 1polandballisacoolcharacternopeOutputYESInput2 2kremowkawadowickakremowkawiedenskaOutputYESInput1 2aabOutputNONoteIn the first example PolandBall knows much more words and wins effortlessly.In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins.
Input5 1polandballisacoolcharacternope
OutputYES
1 second
256 megabytes
['binary search', 'data structures', 'games', 'greedy', 'sortings', 'strings', '*1100']
A. PolandBall and Hypothesistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number".Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any n.InputThe only number in the input is n (1 ≤ n ≤ 1000) — number from the PolandBall's hypothesis. OutputOutput such m that n·m + 1 is not a prime number. Your answer will be considered correct if you output any suitable m such that 1 ≤ m ≤ 103. It is guaranteed the the answer exists.ExamplesInput3Output1Input4Output2NoteA prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.For the first sample testcase, 3·1 + 1 = 4. We can output 1.In the second sample testcase, 4·1 + 1 = 5. We cannot output 1 because 5 is prime. However, m = 2 is okay since 4·2 + 1 = 9, which is not a prime number.
Input3
Output1
2 seconds
256 megabytes
['brute force', 'graphs', 'math', 'number theory', '*800']
E. Dasha and cyclic tabletime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDasha is fond of challenging puzzles: Rubik's Cube 3 × 3 × 3, 4 × 4 × 4, 5 × 5 × 5 and so on. This time she has a cyclic table of size n × m, and each cell of the table contains a lowercase English letter. Each cell has coordinates (i, j) (0 ≤ i < n, 0 ≤ j < m). The table is cyclic means that to the right of cell (i, j) there is the cell , and to the down there is the cell .Dasha has a pattern as well. A pattern is a non-cyclic table of size r × c. Each cell is either a lowercase English letter or a question mark. Each cell has coordinates (i, j) (0 ≤ i < r, 0 ≤ j < c).The goal of the puzzle is to find all the appearance positions of the pattern in the cyclic table.We say that the cell (i, j) of cyclic table is an appearance position, if for every pair (x, y) such that 0 ≤ x < r and 0 ≤ y < c one of the following conditions holds: There is a question mark in the cell (x, y) of the pattern, or The cell of the cyclic table equals to the cell (x, y) of the pattern. Dasha solved this puzzle in no time, as well as all the others she ever tried. Can you solve it?.InputThe first line contains two integers n and m (1 ≤ n, m ≤ 400) — the cyclic table sizes.Each of the next n lines contains a string of m lowercase English characters — the description of the cyclic table.The next line contains two integers r and c (1 ≤ r, c ≤ 400) — the sizes of the pattern.Each of the next r lines contains a string of c lowercase English letter and/or characters '?' — the description of the pattern.OutputPrint n lines. Each of the n lines should contain m characters. Each of the characters should equal '0' or '1'.The j-th character of the i-th (0-indexed) line should be equal to '1', in case the cell (i, j) is an appearance position, otherwise it should be equal to '0'.ExamplesInput5 7qcezchshhedywqwikywqyqckrqztbqexcxz3 2??yw?qOutput00001000001001000000000000000000000Input10 10fwtoayylhwyyaryyjawrywrdzwhscyhnsyyxiphnbnjwzyyjvokkjgseenwngvmiflpcsylxvkwrobwuwyybbcocyyyysijsvqry2 2??yyOutput1000100000000000000100010000000000010000000000000000000000000000000000010000001010000000010000010000Input8 6ibrgxlxqdcsgokbcgitvpetcxgxxigigghzolmlazagpswzv1 4gx??Output000100000001000000000000010001000000000000000000
Input5 7qcezchshhedywqwikywqyqckrqztbqexcxz3 2??yw?q
Output00001000001001000000000000000000000
6 seconds
512 megabytes
['bitmasks', 'brute force', 'fft', 'strings', 'trees', '*2600']
D. Fedor and couponstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAll our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!InputThe first line contains two integers n and k (1 ≤ k ≤ n ≤ 3·105) — the number of coupons Fedor has, and the number of coupons he wants to choose.Each of the next n lines contains two integers li and ri ( - 109 ≤ li ≤ ri ≤ 109) — the description of the i-th coupon. The coupons can be equal.OutputIn the first line print single integer — the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted.In the second line print k distinct integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the ids of the coupons which Fedor should choose.If there are multiple answers, print any of them.ExamplesInput4 21 10040 70120 130125 180Output311 2 Input3 21 1215 2025 30Output01 2 Input5 21 105 1514 5030 7099 100Output213 4 NoteIn the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total.In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.
Input4 21 10040 70120 130125 180
Output311 2
4 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'sortings', '*2100']
C. Vladik and chattime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!InputThe first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line: <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat. <?>:<text> — the format of a message with unknown sender. The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.OutputPrint the information about the t chats in the following format:If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format:<username>:<text>If there are multiple answers, print any of them.ExamplesInput12Vladik netman2?: Hello, Vladik!?: HiOutputnetman: Hello, Vladik!Vladik: HiInput12netman vladik3netman:how are you??:wrong messagevladik:im fineOutputImpossibleInput23netman vladik Fedosik2?: users are netman, vladik, Fedosikvladik: something wrong with this chat4netman tigerrrrr banany2001 klinchuh4?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?klinchuh: yes, coach!?: yes, netmanbanany2001: yes of course.OutputImpossiblenetman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?klinchuh: yes, coach!tigerrrrr: yes, netmanbanany2001: yes of course.
Input12Vladik netman2?: Hello, Vladik!?: Hi
Outputnetman: Hello, Vladik!Vladik: Hi
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dp', 'implementation', 'strings', '*2200']
B. Ilya and tic-tac-toe gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not. The rules of tic-tac-toe on the 4 × 4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal).InputThe tic-tac-toe position is given in four lines.Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn.OutputPrint single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise.ExamplesInputxx...oo.x...oox.OutputYESInputx.oxox..x.o.oo.xOutputNOInputx..x..ooo...x.xoOutputYESInputo.x.o....x..ooxxOutputNONoteIn the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row.In the second example it wasn't possible to win by making single turn.In the third example Ilya could have won by placing X in the last row between two existing Xs.In the fourth example it wasn't possible to win by making single turn.
Inputxx...oo.x...oox.
OutputYES
2 seconds
256 megabytes
['brute force', 'implementation', '*1100']
A. Lesha and array splittingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A.Lesha is tired now so he asked you to split the array. Help Lesha!InputThe first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A.The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A.OutputIf it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes).Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: l1 = 1 rk = n ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them.ExamplesInput31 2 -3OutputYES21 23 3Input89 -12 3 4 -4 -10 7 3OutputYES21 23 8Input10OutputNOInput41 2 3 -5OutputYES41 12 23 34 4
Input31 2 -3
OutputYES21 23 3
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1200']
C. Interactive Bulls and Cows (Hard)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference from the previous problem is the constraint on the number of requests. In this problem your program should guess the answer doing at most 7 requests.This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java — call System.out.flush(), and in Pascal — flush(output).Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers — the number of "bulls" and the number of "cows". A try can contain equal digits.More formally, let's the secret string is s and the second player are trying to guess it with a string x. The number of "bulls" is a number of such positions i (1 ≤ i ≤ 4) where s[i] = x[i]. The number of "cows" is a number of such digits c that s contains c in the position i (i.e. s[i] = c), x contains c, but x[i] ≠ c.For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.In this problem you are to guess the string s that the system has chosen. You only know that the chosen string consists of 4 distinct digits.You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons — the program either guessed the number x or made an invalid action (for example, printed letters instead of digits).Your program is allowed to do at most 7 queries.You can hack solutions of other participants providing a 4-digit string containing distinct digits — the secret string.InputTo read answers to the queries, the program must use the standard input.The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string s and the string xi printed by your program. If the system response equals "4 0", then your solution should terminate.The testing system will let your program read the i-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value xi in a single line and executes operation flush.OutputThe program must use the standard output to print queries.Your program must output requests — 4-digit strings x1, x2, ..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input.Your program is allowed to do at most 7 queries.ExamplesInput0 12 01 10 42 14 0Output800001793159321001120123NoteThe secret string s in the example is "0123".
Input0 12 01 10 42 14 0
Output800001793159321001120123
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'interactive', '*2500']
B. Interactive Bulls and Cows (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java — call System.out.flush(), and in Pascal — flush(output).Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers — the number of "bulls" and the number of "cows". A try can contain equal digits.More formally, let's the secret string is s and the second player are trying to guess it with a string x. The number of "bulls" is a number of such positions i (1 ≤ i ≤ 4) where s[i] = x[i]. The number of "cows" is a number of such digits c that s contains c in the position i (i.e. s[i] = c), x contains c, but x[i] ≠ c.For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.In this problem you are to guess the string s that the system has chosen. You only know that the chosen string consists of 4 distinct digits.You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons — the program either guessed the number x or made an invalid action (for example, printed letters instead of digits).Your program is allowed to do at most 50 queries.You can hack solutions of other participants providing a 4-digit string containing distinct digits — the secret string.InputTo read answers to the queries, the program must use the standard input.The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string s and the string xi printed by your program. If the system response equals "4 0", then your solution should terminate.The testing system will let your program read the i-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value xi in a single line and executes operation flush.OutputThe program must use the standard output to print queries.Your program must output requests — 4-digit strings x1, x2, ..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input.Your program is allowed to do at most 50 queries.ExamplesInput0 12 01 10 42 14 0Output800001793159321001120123NoteThe secret string s in the example is "0123".
Input0 12 01 10 42 14 0
Output800001793159321001120123
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', '*1600']
A. Santa Claus and Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta Claus has n candies, he dreams to give them as gifts to children.What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has.InputThe only line contains positive integer number n (1 ≤ n ≤ 1000) — number of candies Santa Claus has.OutputPrint 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.ExamplesInput5Output22 3Input9Output33 5 1Input2Output12
Input5
Output22 3
1 second
256 megabytes
['dp', 'greedy', 'math', '*1000']
H. New Year and Snowy Gridtime limit per test9 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPay attention to the output section below, where you will see the information about flushing the output.Bearland is a grid with h rows and w columns. Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right. Every cell is either allowed (denoted by '.' in the input) or permanently blocked (denoted by '#').Bearland is a cold land, where heavy snow often makes travelling harder. Every day a few allowed cells are temporarily blocked by snow. Note, that this block works only on this particular day and next day any of these cells might be allowed again (unless there is another temporarily block).It's possible to move directly between two cells only if they share a side and none of them is permanently or temporarily blocked.Limak is a little polar bear who lives in Bearland. His house is at the top left cell, while his school is at the bottom right cell. Every day Limak should first go from his house to the school and then return back to his house. Since he gets bored easily, he doesn't want to visit the same cell twice on one day, except for the cell with his house, where he starts and ends. If Limak can reach a school and return home avoiding revisiting cells, he calls a day interesting.There are q days you must process, one after another. For each of these days you should check if it's interesting and print "YES" or "NO" on a separate line. In order to be able to read the description of the next day you should print the answer for the previous one and flush the output.It's guaranteed that a day with no cells temporarily blocked by snow would be interesting. It's also guaranteed that cells with Limak's house and school are never blocked (neither permanently or temporarily).InputThe first line of the input contains three integers h, w and q (2 ≤ h, w ≤ 1000, 1 ≤ q ≤ 10 000) — the height and the width of the grid, and the number of days, respectively.Next h lines describe which cells are allowed and which permanently blocked. The i-th line contains a string of length w, describing the i-th row. Every character is either '.' (denoting an allowed cell) or '#' (denoting a permanently blocked cell). It's guaranteed that a day with no cells temporarily blocked by snow would be interesting.Then, the description of q days is given. The description of the i-th day starts with a line containing a single integer ki (1 ≤ ki ≤ 10) — the number of cells that are temporarily blocked by snow on that day. Each of next ki lines contains two integers ri, j and ci, j (1 ≤ ri, j ≤ h, 1 ≤ ci, j ≤ w), representing a cell at the intersection of the row ri, j and the column ci, j. The given ki cells are distinct and none of them is permanently blocked. Also, none of them contains Limak's house or school.OutputFor each of q days print "YES" if that day is interesting, and otherwise print "NO", both without the quotes. After printing an answer, you have to both print the end-of-line character and flush the output. Then you can proceed to the next day. You can get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output.To flush you can use (just after printing a YES/NO and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. ExamplesInput3 5 4...........#...11 411 522 43 121 53 3OutputNOYESYESNOInput9 31 5...............................................................###.###.#.###...###.###.#.###....#.#.#.#.#.......#.#.#.#...#..###.#.#.#.###...###.#.#.#...#..#...#.#.#.#.#...#...#.#.#...#..###.###.#.###...###.###.#...#...............................................................56 52 111 148 152 1452 141 148 166 52 1132 21 48 30103 13 115 167 214 163 57 313 97 253 27103 13 97 253 277 214 173 57 314 163 11OutputNOYESYESYESNONoteIn the first sample, there are 4 days. Drawings below show how Limak could go to school and return to his home in the second and the third day (on the left and on the right respectively). A permanently blocked cell is painted red, while cells temporarily blocked by snow are painted orange. Black and green arrows should Limak's way to the school and back to the house respectively. For the second sample, below you can see how the grid looks like on each day, where '#' denotes a cell that is blocked, either temporarily or permanently.
Input3 5 4...........#...11 411 522 43 121 53 3
OutputNOYESYESNO
9 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'interactive', '*3500']
G. New Year and Binary Tree Pathstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe New Year tree is an infinite perfect binary tree rooted in the node 1. Each node v has two children: nodes indexed (2·v) and (2·v + 1). Polar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of nodes. Though he was given an opportunity to pick the pair himself! Now he wants to know the number of unordered pairs of indices (u, v) (u ≤ v), such that the sum of indices of all nodes along the simple path between u and v (including endpoints) is equal to s. Can you help him and count this value?InputThe only line of the input contains a single integer s (1 ≤ s ≤ 1015).OutputPrint one integer, denoting the number of unordered pairs of nodes indices defining simple paths with the sum of indices of vertices equal to s.ExampleInput10Output4NoteIn sample test, there are 4 paths with the sum of indices equal to 10:
Input10
Output4
3 seconds
256 megabytes
['bitmasks', 'brute force', 'combinatorics', 'dp', '*3200']
F. New Year and Finding Rootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. In the interaction section below you will find the information about flushing the output.The New Year tree of height h is a perfect binary tree with vertices numbered 1 through 2h - 1 in some order. In this problem we assume that h is at least 2. The drawing below shows one example New Year tree of height 3: Polar bears love decorating the New Year tree and Limak is no exception. To decorate the tree, he must first find its root, i.e. a vertex with exactly two neighbours (assuming that h ≥ 2). It won't be easy because Limak is a little bear and he doesn't even see the whole tree. Can you help him?There are t testcases. In each testcase, you should first read h from the input. Then you can ask at most 16 questions of format "? x" (without quotes), where x is an integer between 1 and 2h - 1, inclusive. As a reply you will get the list of neighbours of vertex x (more details in the "Interaction" section below). For example, for a tree on the drawing above after asking "? 1" you would get a response with 3 neighbours: 4, 5 and 7. Your goal is to find the index of the root y and print it in the format "! y". You will be able to read h for a next testcase only after printing the answer in a previous testcase and flushing the output.Each tree is fixed from the beginning and it doesn't change during your questions.InputThe first line of the input contains a single integer t (1 ≤ t ≤ 500) — the number of testcases.At the beginning of each testcase you should read from the input a single integer h (2 ≤ h ≤ 7) — the height of the tree. You can't read the value of h in a next testcase until you answer a previous testcase.InteractionTo ask a question about neighbours of vertex x, print "? x" (without quotes) on a separate line. Note, you must print an end-of-line character after the last character of the line and flush your output to get a response.The response will consist of two lines. The first line will contain a single integer k (1 ≤ k ≤ 3) — the number of neighbours of vertex x. The second line will contain k distinct integers t1, ..., tk (1 ≤ t1 < ... < tk ≤ 2h - 1) — indices of neighbours of vertex x, gives in the increasing order.After asking at most 16 questions you have to say y — the index of the root. Print "! y" (without quotes) and an end-of-line character, and flush the output.Each tree is fixed from the beginning and it doesn't change during your questions.You can get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output.To flush you can use (just printing a query/answer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. In any moment if the program reads h = 0 or k = 0 it should immediately terminate normally (for example, calling exit(0)). It means that the system detected incorrect request/output from your program and printed 0 because if can't process your requests anymore. In this case you'll receive verdict "Wrong Answer", but if you ignore case h = 0 or k = 0 it could lead to "Runtime Error", "Time/Memory limit exceeded" or any other verdict because your program could read a trash from the closed input stream.Hacking. To hack someone, use the following format:The first line should contain a single integer t equal to 1 (only one testcase is allowed in hacks). The second line should contain a single integer h. Each of next 2h - 2 lines should contain two distinct integers ai and bi (1 ≤ ai, bi ≤ 2h - 1), denoting two nodes connected with an edge. The printed edges must form a perfect binary tree of height h.Of course, contestant programs will not be able to see this input.ExamplesInput1334 5 721 212Output? 1? 5? 6! 5Input221321 221 2433 12 13Output? 1? 3? 3! 3? 6! 1NoteIn the first sample, a tree corresponds to the drawing from the statement.In the second sample, there are two two testcases. A tree in the first testcase has height 2 and thus 3 vertices. A tree in the second testcase has height 4 and thus 15 vertices. You can see both trees on the drawing below.
Input1334 5 721 212
Output? 1? 5? 6! 5
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'interactive', 'trees', '*2800']
E. New Year and Old Subsequencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is  - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive).InputThe first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively.The second line contains a string s of length n. Every character is one of digits '0'–'9'.The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query.OutputFor each query print the ugliness of the given substring.ExamplesInput8 3201667661 81 72 8Output43-1Input15 50120166620916703 41 144 151 1310 15Output-121-1-1Input4 212342 41 2Output-1-1NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") =  - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170".
Input8 3201667661 81 72 8
Output43-1
3 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', 'matrices', '*2600']
D. New Year and Fireworkstime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on.Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time — it is allowed and such parts do not crash.Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells?InputThe first line of the input contains a single integer n (1 ≤ n ≤ 30) — the total depth of the recursion.The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding.OutputPrint one integer, denoting the number of cells which will be visited at least once by any part of the firework.ExamplesInput44 2 2 3Output39Input61 1 1 1 1 3Output85Input13Output3NoteFor the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level.
Input44 2 2 3
Output39
2.5 seconds
256 megabytes
['brute force', 'data structures', 'dfs and similar', 'dp', 'implementation', '*1900']
C. New Year and Ratingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".InputThe first line of the input contains a single integer n (1 ≤ n ≤ 200 000).The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.OutputIf Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.ExamplesInput3-7 15 28 2Output1907Input257 122 2OutputImpossibleInput1-5 1OutputInfinityInput427 213 1-50 18 2Output1897NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating: Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7. With rating 1894 Limak is in the division 2. His rating increases by 5. Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.
Input3-7 15 28 2
Output1907
2 seconds
256 megabytes
['binary search', 'greedy', 'math', '*1600']
B. New Year and North Poletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East".Limak isn’t sure whether the description is valid. You must help him to check the following conditions: If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 50).The i-th of next n lines contains an integer ti and a string diri (1 ≤ ti ≤ 106, ) — the length and the direction of the i-th part of the journey, according to the description Limak got.OutputPrint "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes.ExamplesInput57500 South10000 East3500 North4444 West4000 NorthOutputYESInput215000 South4000 EastOutputNOInput520000 South1000 North1000000 West9000 North10000 NorthOutputYESInput320000 South10 East20000 NorthOutputNOInput21000 North1000 SouthOutputNOInput450 South50 North15000 South15000 NorthOutputYESNoteDrawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole.
Input57500 South10000 East3500 North4444 West4000 North
OutputYES
2 seconds
256 megabytes
['geometry', 'implementation', '*1300']
A. New Year and Hurrytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th problem.Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs k minutes to get there from his house, where he will participate in the contest first.How many problems can Limak solve if he wants to make it to the party?InputThe only line of the input contains two integers n and k (1 ≤ n ≤ 10, 1 ≤ k ≤ 240) — the number of the problems in the contest and the number of minutes Limak needs to get to the party from his house.OutputPrint one integer, denoting the maximum possible number of problems Limak can solve so that he could get to the party at midnight or earlier.ExamplesInput3 222Output2Input4 190Output4Input7 1Output7NoteIn the first sample, there are 3 problems and Limak needs 222 minutes to get to the party. The three problems require 5, 10 and 15 minutes respectively. Limak can spend 5 + 10 = 15 minutes to solve first two problems. Then, at 20:15 he can leave his house to get to the party at 23:57 (after 222 minutes). In this scenario Limak would solve 2 problems. He doesn't have enough time to solve 3 problems so the answer is 2.In the second sample, Limak can solve all 4 problems in 5 + 10 + 15 + 20 = 50 minutes. At 20:50 he will leave the house and go to the party. He will get there exactly at midnight.In the third sample, Limak needs only 1 minute to get to the party. He has enough time to solve all 7 problems.
Input3 222
Output2
1 second
256 megabytes
['binary search', 'brute force', 'implementation', 'math', '*800']
E. Inversions After Shuffletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: Pick a random segment (continuous subsequence) from l to r. All segments are equiprobable. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable. This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above.InputThe first line contains a single integer n (1 ≤ n ≤ 100 000) — the length of the permutation.The second line contains n distinct integers from 1 to n — elements of the permutation.OutputPrint one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExampleInput32 3 1Output1.916666666666666666666666666667
Input32 3 1
Output1.916666666666666666666666666667
1 second
256 megabytes
['data structures', 'probabilities', '*2400']
D. Leaving Auctiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi < bi + 1 for all i < n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i < n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.InputThe first line of the input contains an integer n (1 ≤ n ≤ 200 000) — the number of participants and bids.Each of the following n lines contains two integers ai and bi (1 ≤ ai ≤ n, 1 ≤ bi ≤ 109, bi < bi + 1) — the number of participant who made the i-th bid and the size of this bid.Next line contains an integer q (1 ≤ q ≤ 200 000) — the number of question you have in mind.Each of next q lines contains an integer k (1 ≤ k ≤ n), followed by k integers lj (1 ≤ lj ≤ n) — the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question.It's guaranteed that the sum of k over all question won't exceed 200 000.OutputFor each question print two integer — the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.ExamplesInput61 102 1003 10001 100002 1000003 100000031 32 2 32 1 2Output2 1000001 103 1000Input31 102 1001 100022 1 22 2 3Output0 01 10NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Input61 102 1003 10001 100002 1000003 100000031 32 2 32 1 2
Output2 1000001 103 1000
2 seconds
256 megabytes
['binary search', 'data structures', '*2000']
C. Votingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated: Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting). When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction. You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of employees. The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.OutputPrint 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.ExamplesInput5DDRRROutputDInput6DDRRRROutputRNoteConsider one of the voting scenarios for the first sample: Employee 1 denies employee 5 to vote. Employee 2 denies employee 3 to vote. Employee 3 has no right to vote and skips his turn (he was denied by employee 2). Employee 4 denies employee 2 to vote. Employee 5 has no right to vote and skips his turn (he was denied by employee 1). Employee 1 denies employee 4. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Input5DDRRR
OutputD
1 second
256 megabytes
['greedy', 'implementation', 'two pointers', '*1500']
B. Parallelogram is Backtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLong time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwise traversal.Alex had very nice test for this problem, but is somehow happened that the last line of the input was lost and now he has only three out of four points of the original parallelogram. He remembers that test was so good that he asks you to restore it given only these three points.InputThe input consists of three lines, each containing a pair of integer coordinates xi and yi ( - 1000 ≤ xi, yi ≤ 1000). It's guaranteed that these three points do not lie on the same line and no two of them coincide.OutputFirst print integer k — the number of ways to add one new integer point such that the obtained set defines some parallelogram of positive area. There is no requirement for the points to be arranged in any special order (like traversal), they just define the set of vertices.Then print k lines, each containing a pair of integer — possible coordinates of the fourth point.ExampleInput0 01 00 1Output31 -1-1 11 1NoteIf you need clarification of what parallelogram is, please check Wikipedia page:https://en.wikipedia.org/wiki/Parallelogram
Input0 01 00 1
Output31 -1-1 11 1
1 second
256 megabytes
['brute force', 'constructive algorithms', 'geometry', '*1200']
A. Bachgold Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k. InputThe only line of the input contains a single integer n (2 ≤ n ≤ 100 000).OutputThe first line of the output contains a single integer k — maximum possible number of primes in representation.The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.ExamplesInput5Output22 3Input6Output32 2 2
Input5
Output22 3
1 second
256 megabytes
['greedy', 'implementation', 'math', 'number theory', '*800']
F. Santa Clauses and a Soccer Championshiptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe country Treeland consists of n cities connected with n - 1 bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly 2k teams from 2k different cities.During the first stage all teams are divided into k pairs. Teams of each pair play two games against each other: one in the hometown of the first team, and the other in the hometown of the other team. Thus, each of the 2k cities holds exactly one soccer game. However, it's not decided yet how to divide teams into pairs.It's also necessary to choose several cities to settle players in. Organizers tend to use as few cities as possible to settle the teams.Nobody wants to travel too much during the championship, so if a team plays in cities u and v, it wants to live in one of the cities on the shortest path between u and v (maybe, in u or in v). There is another constraint also: the teams from one pair must live in the same city.Summarizing, the organizers want to divide 2k teams into pairs and settle them in the minimum possible number of cities m in such a way that teams from each pair live in the same city which lies between their hometowns.InputThe first line of input contains two integers n and k (2 ≤ n ≤ 2·105, 2 ≤ 2k ≤ n) — the number of cities in Treeland and the number of pairs of teams, respectively.The following n - 1 lines describe roads in Treeland: each of these lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b) which mean that there is a road between cities a and b. It's guaranteed that there is a path between any two cities.The last line contains 2k distinct integers c1, c2, ..., c2k (1 ≤ ci ≤ n), where ci is the hometown of the i-th team. All these numbers are distinct.OutputThe first line of output must contain the only positive integer m which should be equal to the minimum possible number of cities the teams can be settled in.The second line should contain m distinct numbers d1, d2, ..., dm (1 ≤ di ≤ n) denoting the indices of the cities where the teams should be settled.The k lines should follow, the j-th of them should contain 3 integers uj, vj and xj, where uj and vj are the hometowns of the j-th pair's teams, and xj is the city they should live in during the tournament. Each of the numbers c1, c2, ..., c2k should occur in all uj's and vj's exactly once. Each of the numbers xj should belong to {d1, d2, ..., dm}.If there are several possible answers, print any of them.ExampleInput6 21 21 32 42 53 62 5 4 6Output125 4 26 2 2NoteIn the first test the orginizers can settle all the teams in the city number 2. The way to divide all teams into pairs is not important, since all requirements are satisfied anyway, because the city 2 lies on the shortest path between every two cities from {2, 4, 5, 6}.
Input6 21 21 32 42 53 62 5 4 6
Output125 4 26 2 2
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'trees', '*2300']
E. Santa Claus and Tangerinestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta Claus has n tangerines, and the i-th of them consists of exactly ai slices. Santa Claus came to a school which has k pupils. Santa decided to treat them with tangerines.However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so that no one will be offended. In order to do this, he can divide a tangerine or any existing part into two smaller equal parts. If the number of slices in the part he wants to split is odd, then one of the resulting parts will have one slice more than the other. It's forbidden to divide a part consisting of only one slice.Santa Claus wants to present to everyone either a whole tangerine or exactly one part of it (that also means that everyone must get a positive number of slices). One or several tangerines or their parts may stay with Santa.Let bi be the number of slices the i-th pupil has in the end. Let Santa's joy be the minimum among all bi's.Your task is to find the maximum possible joy Santa can have after he treats everyone with tangerines (or their parts).InputThe first line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 2·109) denoting the number of tangerines and the number of pupils, respectively.The second line consists of n positive integers a1, a2, ..., an (1 ≤ ai ≤ 107), where ai stands for the number of slices the i-th tangerine consists of.OutputIf there's no way to present a tangerine or a part of tangerine to everyone, print -1. Otherwise, print the maximum possible joy that Santa can have.ExamplesInput3 25 9 3Output5Input2 412 14Output6Input2 31 1Output-1NoteIn the first example Santa should divide the second tangerine into two parts with 5 and 4 slices. After that he can present the part with 5 slices to the first pupil and the whole first tangerine (with 5 slices, too) to the second pupil.In the second example Santa should divide both tangerines, so that he'll be able to present two parts with 6 slices and two parts with 7 slices.In the third example Santa Claus can't present 2 slices to 3 pupils in such a way that everyone will have anything.
Input3 25 9 3
Output5
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'two pointers', '*2100']
D. Santa Claus and a Palindrometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string si having the same length n. We denote the beauty of the i-th string by ai. It can happen that ai is negative — that means that Santa doesn't find this string beautiful at all.Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length n.Recall that a palindrome is a string that doesn't change after one reverses it.Since the empty string is a palindrome too, the answer can't be negative. Even if all ai's are negative, Santa can obtain the empty string.InputThe first line contains two positive integers k and n divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1 ≤ k, n ≤ 100 000; n·k  ≤ 100 000).k lines follow. The i-th of them contains the string si and its beauty ai ( - 10 000 ≤ ai ≤ 10 000). The string consists of n lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties.OutputIn the only line print the required maximum possible beauty.ExamplesInput7 3abb 2aaa -3bba -1zyz -4abb 5aaa 7xyx 4Output12Input3 1a 1a 2a 3Output6Input2 5abcde 10000abcde 10000Output0NoteIn the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order).
Input7 3abb 2aaa -3bba -1zyz -4abb 5aaa 7xyx 4
Output12
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*2100']
C. Santa Claus and Robottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p1, it'll move to p2, again, choosing one of the shortest ways, then to p3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.InputThe first line of input contains the only positive integer n (1 ≤ n ≤ 2·105) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R — to the right, U — to the top and D — to the bottom. Have a look at the illustrations for better explanation.OutputThe only line of input should contain the minimum possible length of the sequence.ExamplesInput4RURDOutput2Input6RRULDDOutput2Input26RRRULURURUULULLLDLDDRDRDLDOutput7Input3RLLOutput2Input4LRLROutput4NoteThe illustrations to the first three tests are given below. The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.
Input4RURD
Output2
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1400']
B. Santa Claus and Keyboard Checktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.InputThe input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.OutputIf Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.ExamplesInputhelloworldehoolwlrozOutput3h el od zInputhastalavistababyhastalavistababyOutput0InputmerrychristmaschristmasmerryOutput-1
Inputhelloworldehoolwlroz
Output3h el od z
2 seconds
256 megabytes
['implementation', 'strings', '*1500']
A. Santa Claus and a Place in a Classtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta 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 2nm. The places are numbered by lanes (i. e. 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. e. 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!InputThe only line contains three integers n, m and k (1 ≤ n, m ≤ 10 000, 1 ≤ k ≤ 2nm) — the number of lanes, the number of desks in each lane and the number of Santa Claus' place.OutputPrint 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.ExamplesInput4 3 9Output2 2 LInput4 3 24Output4 3 RInput2 4 4Output1 2 RNoteThe 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.
Input4 3 9
Output2 2 L
2 seconds
256 megabytes
['implementation', 'math', '*800']
F. Igor and Interesting Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor likes hexadecimal notation and considers positive integer in the hexadecimal notation interesting if each digit and each letter in it appears no more than t times. For example, if t = 3, then integers 13a13322, aaa, abcdef0123456789 are interesting, but numbers aaaa, abababab and 1000000 are not interesting.Your task is to find the k-th smallest interesting for Igor integer in the hexadecimal notation. The integer should not contain leading zeros.InputThe first line contains the two integers k and t (1 ≤ k ≤ 2·109, 1 ≤ t ≤ 10) — the number of the required integer and the maximum number of times some integer or letter can appear in interesting integer.It can be shown that the answer always exists for such constraints.OutputPrint in the hexadecimal notation the only integer that is the k-th smallest interesting integer for Igor.ExamplesInput17 1Output12Input1000000 2Outputfca2cNoteThe first 20 interesting integers if t = 1: 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, 10, 12, 13, 14, 15. So the answer for the first example equals 12.
Input17 1
Output12
2 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'math', '*2500']
E. Commentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment.When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: at first, the text of the comment is written; after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). All elements in this format are separated by single comma. Similarly, the comments of the first level are separated by comma.For example, if the comments look like: then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: at first, print a integer d — the maximum depth of nesting comments; after that print d lines, the i-th of them corresponds to nesting level i; for the i-th row print comments of nesting level i in the order of their appearance in the Policarp's comments feed, separated by space. InputThe first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas. It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and either equals 0 or does not contain leading zeros.The length of the whole string does not exceed 106. It is guaranteed that given structure of comments is valid. OutputPrint comments in a format that is given in the statement. For each level of nesting, comments should be printed in the order they are given in the input.ExamplesInputhello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0Output3hello test one ok bye two a b Inputa,5,A,0,a,0,A,0,a,0,A,0Output2a A a A a A InputA,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0Output4A K M B F H L N O C D G I P E J NoteThe first example is explained in the statements.
Inputhello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0
Output3hello test one ok bye two a b
2 seconds
256 megabytes
['dfs and similar', 'expression parsing', 'implementation', 'strings', '*1700']
D. Winter Is Comingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day. Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative. Vasya can change summer tires to winter tires and vice versa at the beginning of any day.Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.InputThe first line contains two positive integers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total.The second line contains a sequence of n integers t1, t2, ..., tn ( - 20 ≤ ti ≤ 20) — the average air temperature in the i-th winter day. OutputPrint the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.ExamplesInput4 3-5 20 -3 0Output2Input4 2-5 20 -3 0Output4Input10 62 -5 1 3 0 0 -4 -3 1 0Output3NoteIn the first example before the first winter day Vasya should change summer tires to winter tires, use it for three days, and then change winter tires to summer tires because he can drive safely with the winter tires for just three days. Thus, the total number of tires' changes equals two. In the second example before the first winter day Vasya should change summer tires to winter tires, and then after the first winter day change winter tires to summer tires. After the second day it is necessary to change summer tires to winter tires again, and after the third day it is necessary to change winter tires to summer tires. Thus, the total number of tires' changes equals four.
Input4 3-5 20 -3 0
Output2
1 second
256 megabytes
['dp', 'greedy', 'sortings', '*1800']
C. Serverstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to perform it, and di — the time needed to perform this task in seconds. All ti are distinct.To perform the i-th task you need ki servers which are unoccupied in the second ti. After the servers begin to perform the task, each of them will be busy over the next di seconds. Thus, they will be busy in seconds ti, ti + 1, ..., ti + di - 1. For performing the task, ki servers with the smallest ids will be chosen from all the unoccupied servers. If in the second ti there are not enough unoccupied servers, the task is ignored.Write the program that determines which tasks will be performed and which will be ignored.InputThe first line contains two positive integers n and q (1 ≤ n ≤ 100, 1 ≤ q ≤ 105) — the number of servers and the number of tasks. Next q lines contains three integers each, the i-th line contains integers ti, ki and di (1 ≤ ti ≤ 106, 1 ≤ ki ≤ n, 1 ≤ di ≤ 1000) — the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds. OutputPrint q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.ExamplesInput4 31 3 22 2 13 4 3Output6-110Input3 23 2 35 1 2Output33Input8 61 3 204 2 16 5 510 1 115 3 621 8 8Output6930-11536NoteIn the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10).In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task.
Input4 31 3 22 2 13 4 3
Output6-110
2 seconds
256 megabytes
['implementation', '*1300']
B. Mammoth's Genome Decodingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.InputThe first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome.The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.OutputIf it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).ExamplesInput8AG?C??CTOutputAGACGTCTInput4AGCTOutputAGCTInput6????G?Output===Input4AA??Output===NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom.
Input8AG?C??CT
OutputAGACGTCT
1 second
256 megabytes
['implementation', 'strings', '*900']
A. Display Sizetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels. Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that: there are exactly n pixels on the display; the number of rows does not exceed the number of columns, it means a ≤ b; the difference b - a is as small as possible. InputThe first line contains the positive integer n (1 ≤ n ≤ 106) — the number of pixels display should have.OutputPrint two integers — the number of rows and columns on the display. ExamplesInput8Output2 4Input64Output8 8Input5Output1 5Input999999Output999 1001NoteIn the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels.
Input8
Output2 4
1 second
256 megabytes
['brute force', 'math', '*800']
G. New Roadstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland, each of them has a unique id — an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roads — there are no roads.That is why there was a decision to build n - 1 roads so that there will be exactly one simple path between each pair of cities.In the construction plan t integers a1, a2, ..., at were stated, where t equals to the distance from the capital to the most distant city, concerning new roads. ai equals the number of cities which should be at the distance i from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another. Also, it was decided that among all the cities except the capital there should be exactly k cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it. Your task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.InputThe first line contains three positive numbers n, t and k (2 ≤ n ≤ 2·105, 1 ≤ t, k < n) — the distance to the most distant city from the capital and the number of cities which should be dead-ends (the capital in this number is not taken into consideration). The second line contains a sequence of t integers a1, a2, ..., at (1 ≤ ai < n), the i-th number is the number of cities which should be at the distance i from the capital. It is guaranteed that the sum of all the values ai equals n - 1.OutputIf it is impossible to built roads which satisfy all conditions, print -1.Otherwise, in the first line print one integer n — the number of cities in Berland. In the each of the next n - 1 line print two integers — the ids of cities that are connected by a road. Each road should be printed exactly once. You can print the roads and the cities connected by a road in any order.If there are multiple answers, print any of them. Remember that the capital has id 1.ExamplesInput7 3 32 3 1Output71 32 12 62 47 43 5Input14 5 64 4 2 2 1Output143 11 411 61 210 136 1010 1214 128 45 13 72 65 9Input3 1 12Output-1
Input7 3 32 3 1
Output71 32 12 62 47 43 5
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'trees', '*2100']
F. Music in Cartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha reaches the work by car. It takes exactly k minutes. On his way he listens to music. All songs in his playlist go one by one, after listening to the i-th song Sasha gets a pleasure which equals ai. The i-th song lasts for ti minutes. Before the beginning of his way Sasha turns on some song x and then he listens to the songs one by one: at first, the song x, then the song (x + 1), then the song number (x + 2), and so on. He listens to songs until he reaches the work or until he listens to the last song in his playlist. Sasha can listen to each song to the end or partly.In the second case he listens to the song for integer number of minutes, at least half of the song's length. Formally, if the length of the song equals d minutes, Sasha listens to it for no less than minutes, then he immediately switches it to the next song (if there is such). For example, if the length of the song which Sasha wants to partly listen to, equals 5 minutes, then he should listen to it for at least 3 minutes, if the length of the song equals 8 minutes, then he should listen to it for at least 4 minutes.It takes no time to switch a song.Sasha wants to listen partly no more than w songs. If the last listened song plays for less than half of its length, then Sasha doesn't get pleasure from it and that song is not included to the list of partly listened songs. It is not allowed to skip songs. A pleasure from a song does not depend on the listening mode, for the i-th song this value equals ai.Help Sasha to choose such x and no more than w songs for partial listening to get the maximum pleasure. Write a program to find the maximum pleasure Sasha can get from the listening to the songs on his way to the work.InputThe first line contains three integers n, w and k (1 ≤ w ≤ n ≤ 2·105, 1 ≤ k ≤ 2·109) — the number of songs in the playlist, the number of songs Sasha can listen to partly and time in minutes which Sasha needs to reach work. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 104), where ai equals the pleasure Sasha gets after listening to the i-th song.The third line contains n positive integers t1, t2, ..., tn (2 ≤ ti ≤ 104), where ti equals the length of the i-th song in minutes.OutputPrint the maximum pleasure Sasha can get after listening to the songs on the way to work. ExamplesInput7 2 113 4 3 5 1 4 67 7 3 6 5 3 9Output12Input8 4 205 6 4 3 7 5 4 110 12 5 12 14 8 5 8Output19Input1 1 569Output6Input1 1 347Output0NoteIn the first example Sasha needs to start listening from the song number 2. He should listen to it partly (for 4 minutes), then listen to the song number 3 to the end (for 3 minutes) and then partly listen to the song number 4 (for 3 minutes). After listening to these songs Sasha will get pleasure which equals 4 + 3 + 5 = 12. Sasha will not have time to listen to the song number 5 because he will spend 4 + 3 + 3 = 10 minutes listening to songs number 2, 3 and 4 and only 1 minute is left after that.
Input7 2 113 4 3 5 1 4 67 7 3 6 5 3 9
Output12
1 second
256 megabytes
['data structures', 'greedy', 'two pointers', '*2200']