task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Strings (STRSOCU) This problem features a story of a certain Black Kitten. Perhaps you saw a funny image where a few kittens sit and think about some mundane stuff, like “I want this”, “I want that”, while the black one thinks “I want to rule the Universe”... Well, that’s true! The Black Kitten took a long sheet of paper and wrote a String on it. That String should give him power to rule the Universe!.. (Or was he just going to win ACM ICPC Finals in 2013 with it?) The sad thing is that we’ll never know for sure because of other kittens and their stupid games. As you may know, many kittens like to shred furniture, wallpaper and other stuff like that. To make a long story short, a certain White Kitten shred the paper on which the String was written! No more ultimate power for the Black one. (What a mess.) Luckily, the String was only cut into two parts: the First part and the Second one. The Black Kitten now performs some rituals with the two parts. That, he believes, will help him gain some of the magical power. (Or maybe he is just practicing for the Finals?) Anyway, right now, the Black Kitten calculates the number of different substrings of the First part that occur in the Second part exactly K times. Two or more occurrences may overlap. Two substrings are considered different if they are not equal as strings. You may try and calculate the answer for him. Perhaps some of the power will be yours, too. (At the very least, you have a chance to improve your programming and problem solving skills by doing so.) Input The first line of input contains an integer T that represents the number of test cases. Every following test case is three lines, The first line of test case contains the First part of the String. The second line contains the Second part. Each of the parts is a non-empty string consisting of lowercase English letters, and the size of each is no more than 8,000 characters. The third line contains one positive integer K not exceeding the length of each of the given parts. Output For each test case, output on a single line “Case #T:” where T is the number of the test case, followed by a line contains one integer: the number of different substrings of the First part that occur in the Second part exactly K times. Example Input: 3 egyptnational ecpc 1 egyptnational ecpc 2 fastlast bestmost 2 Output: Case #1: 2 Case #2: 0 Case #3: 3
33,000
Fatawy (FATAWY) Fatawy is one of the most popular social networking site in Egypt during the last period. Every user is posting Fatwa through his profile to share his thoughts with his followers. And everyone can re-post a Fatwa and make some small modifications to this Fatwa before re-posting it. Zezo was interested to analyze all Fatawy from his followers and know what are the trending topics they are discussing in Egypt on a given day. So he tried to model a system to extract some features from every Fatwa, such that every Fatwa can be represented by at most 10 features and every feature is represented by one Capital Alphabetic character. And through his system he decided to define a relation between Fatawy, that's fatwa 'A' is on the same topic as Fatwa 'B', if values of fractions length(lcs)/length(A) and length(lcs)/length(B) in percent must both be bigger than TH where: lcs is the longest common subsequence of the feature vector of Fatwa 'A' and feature vector of Fatwa 'B' and TH is a threshold percentage of the Fatwa length. If Fatwa 'A' is on the same topic of Fatwa 'B', and Fatwa 'A' is on the same topic of Fatwa 'C', then Fatwa 'B' is on the same topic of fatwa 'C'. (See sample 1 for details). So as you all know that Zezo is not that good at programming and implementing this system, he will just help you by giving you the feature vector of every Fatwa, and he kindly ask you to find the number of different topics in that day. Note: The longest common subsequence (LCS) problem is to find the longest subsequence common to all sequences in a set of sequences (often just two). And it is good to notice that substrings are consecutive parts of a string, while subsequences need not be. Input The first line of input contains an integer T that represents the number of test cases. Every following test case will start with a line contains two integers N and TH (1 <= N <= 500) number of Fatway in a given day and TH is an integer number in the interval ]0, 100[ which is the threshold percent as explained in the problem description, followed by N lines every line contains a single string F i of uppercase characters where 1 <= length(F i ) <= 10. Output For each test case, output on a single line “Case #T:” where T is the number of the test case, followed by a line contains the number of trending topics in that day. Example Input: 2 3 60 ABC ABB ACC 5 80 BCCBC AAABB CACBC CABCB ABCAB Output: Case #1: 1 Case #2: 2 Explanation the LCS between (ABC, ABB) = 2, Len(ABC) = 3, Len(ABB)=3, Len(ACC)=3 LCS / Len(ABC) = 66.66 >= 60% && LCS / Len(ABB) = 66.66 >= 60% so ABC and ABB considered to be on the same topic. The same Applies for ABC and ACC: (ABC, ABB) are on the same topic, (ABC, ACC) are on the same topic, so (ABC, ACC, ABB) are considered to be on the same topic.
33,001
Pell (Mid pelling) (PELL2) D is a given positive integer, consider the equation : X² = D×Y² + 1, with X and Y positive integers. Find the minimum numbers (X,Y) within all solutions. Sometimes it's possible, sometimes not! Examples : If D=2, 3² = 2×2² + 1, so X=3 and Y=2. If D=3, 2² = 3×1² + 1, so X=2 and Y=1. If D=4, it's impossible! Input The input begins with the number T of test cases in a single line. In each of the next T lines there is one integer D. Output For each test case, if possible print X and Y the answer of the problem for D, else "-1". Example Input: 3 2 3 4 Output: 3 2 2 1 -1 Constraints T <= 1000 1 < D <= 10^7, the numbers D were randomly chosen. (but XerK modified one of them!) 190 bytes of sub-optimal python code can get AC in less than 2.5 seconds, there's many rooms to make faster code. If you have TLE, you should first consider EQU2 first. Edit(2017-02-11, after compiler updates) : New TL at 1.5s. The Python awaited solution ends under 0.8s, pike or java around 1.4s. Some old AC might not keep their AC : here it's mid-pelling. The 'mid' is to be kept in consideration.
33,002
XOR Game (QN01) You are given an array of n integers (0 <= n <= 1000). Find a contiguous subsequence of these numbers [a i , a j ] (1 <= i, j <= n), such that the Exclusive-OR of these numbers is maximum. (That is, a i XOR a i+1 XOR ... a j should be maximum). Input The test case contains exactly 2 lines of input. The first line contains a single integer n (0 <= n <= 1000), the total number of integers in the sequence given to you. The next line contains n space separated integers such that the ith integer denotes a i . (0 <= a i <= 10 9 ). Note that these integers need not necessarily be distinct. Output Output two lines. In the first line, print out the value of the maximum XOR. In the second line, print out i and j with a space separating them, such that [a i , a j ] (both endpoints inclusive) denotes the contiguous subsequence with the maximum XOR value. In case there is more than one subsequence with the maximum XOR value, print out the pair (i, j) such that (i, j) is lexicographically smallest. (Formally, we say that a pair (a, b) is lexicographically smaller than another pair (c, d) if and only if (i) a < c or (ii) a=c and b < d.) NOTE : The subsequence must be non-empty, but may be allowed to contain just one integer. (i.e, in this case, i = j) Example Input #1: 1 4 Output #1: 4 1 1 Input #2: 3 1 2 3 Output #2: 3 1 2 Explanation In the first test case, since there is only one number, the maximum XOR would be simply the value of that number (in this case, 4), and i = j = 1. In the second test case, the maximum XOR value is 3, but there are 2 contiguous subsequences that define the same XOR value - (i) [1, 2] since 1 XOR 2 = 3 (ii) [3, 3] since this subsequence contains just the single integer 3. But since [1, 2] is lexicographically smaller than [3, 3], [1, 2] is the desired output.
33,003
Seating Arrangement (QN02) Problem Statement In DA-IICT, the end sems are just around the corner and it seems like all the students are working very hard. But it's not just students, the professors are hard at work too. In particular, the Dean (Students) is very busy working out the exam seating arrangements for all the students. Now normally, as we all know, the benches in each of the exam halls can seat exactly 2 students. Also, it is ensured that every bench contains exactly 2 students from different batches (so that there is no copying). But in spite of this, the Dean has noticed that even if the 2 students are from totally different batches, if they are friends, then they tend to help each other (or at least try to, depending on how much they both know). The Dean wants to prevent this, so the seating arrangement is such that no two friends sit side by side during any exam, so that the students prepare well for the exams. But he is falling short of ideas to work this out. Please help him out. You are given a list of pairs of IDs ( A, B ), such that the student with ID A is friends with the student with ID B. For every query ( C, D ) please print out whether or not these 2 students are friends ( meaning they cannot be seated with each other ). Note : In this case, please assume friendship to be both symmetric and transitive . That is, if A is friends with B, B is also friends with A. Moreover, if A and B are friends and B and C are friends, this implies that A and C are also friends. Input The input comprises of several lines. The first line contains 2 integers - n and m, where n is the number of students who will be writing the exam ( 2 <= n <= 100000 ) and m is the number of pairs of student IDs in the input. ( 0 <= m <= 100000. Also m <= n*( n+1 ) / 2  ). This is followed by m lines of the form : A B This indicates that the student with ID A is friends with the student with ID B. ( 0 <= A,B < n ).   This is followed by a line containing a single integer q ( 1 <= q <= 100000 ) indicating the number of queries you have to answer. q lines of queries follow. Each query consists of a single line containing 2 space separated integers C and D. ( 0 <= C,D < n ). These are the 2 student IDs for which you have to state whether or not they are friends. Note : All student IDs are unique, and range from 0 to n-1. Output For each query, output a single line with "YES" if the 2 students are friends, and "NO" otherwise. Please note that the quotes are just for clarity, and that the output is case-sensitive.   Example Input: 7 4 1 2 2 3 1 3 4 5 4 1 3 4 6 5 1 5 4 Output: YES NO NO YES
33,004
Colorful Circle (EASY) (CRCLE_UI) ------------------------ I take this problem from my midterm exam today, because for me and some of my friends it's interesting, so I decided to translated this problem into English and upload this problem to SPOJ. See the original problem in Indonesian language here . ------------------------  Given N sectors where 1< N <10 1000 , from a circle that sown in the picture below: We will color each sector with K  different colors, where 2< K <10 1000  such that each sector colored with one color and each adjacent sector must have different color. Your task is to count how many ways to color all that sectors. Input First line, there is a number  T (0< T <1000) denoting number of test cases, then T lines follow. each line containing two integers: N and K  separated by a space. Output For each test case, output number of ways to color the circle, since the number can be too large, take modulo 10 9 +7. Example Input: 2 2 3 3 3 Output: 6 6 Explanation: For the first case, we have two sectors and three colors, here is all possibilities: For second test case, we have three sector and three colors, here is all possibilities:   Time limit set so that ~128 Bytes of python 3 code can get accepted, also my C top speed program AC in 0.12s Have fun :)    See also: Another problem added by Tjandra Satria Gunawan
33,005
Dynamic Assignment Problem (DAP) Description You‘ve been given a N×N matrix {W_ij} containing the cost of a weighted bipartite graph, on this graph, you need to implement the following operations: C i j w : Change Wij to w. X i x0 x1 ... xn-1 : Change all Wij to xj. Y i y0 y1 ... yn-1 : Change all Wji to yj. A : Add a new pair of node to the current bipartite graph, then increase N by 1. The weight of those 2n+1 new edges will be set to 0 by default. Q : Query the current maximum weighted matching. Input N (... following the N×N matrix ...) M (... following the M operation ......) Output ... (for each query, simply print the result.) Example Input 1: 2 1 0 0 1 3 Q C 0 1 9 Q Output 1: 2 9 Input 2: 10 76 98 80 30 87 84 78 75 53 26 85 7 83 15 21 91 47 84 82 78 36 39 49 64 71 14 53 2 82 21 83 31 32 30 78 19 46 95 50 55 50 76 63 54 99 55 50 16 29 26 58 74 77 32 3 91 90 18 34 3 56 23 2 78 84 83 71 41 32 54 53 75 39 29 61 25 42 79 58 2 19 13 65 94 9 33 61 5 1 70 34 56 45 37 72 98 47 40 80 79 20 Q Y 3 62 90 89 41 58 56 34 55 53 53 X 0 7 30 30 76 2 48 8 18 89 88 Q C 2 0 3 C 3 0 0 C 8 0 2 C 1 0 3 C 1 0 6 C 5 0 9 Q A X 10 93 8 56 40 4 56 30 32 59 11 52 Y 10 84 62 26 13 66 21 53 23 54 81 52 Q Y 9 13 38 99 50 20 25 59 7 6 77 82 C 4 0 8 C 6 0 6 C 10 0 8 Q Output 2: 870 849 844 947 899 Restriction We guarantee the N will never be more than 100 even during the running time. The total operation M will less than 10000, and among them the Query Operation will be less than 1000.
33,006
Yet Another Counting Problem (TRI2) You have a piece of iron wire with length of n unit. Now you decide to cut it into several ordered pieces and fold each piece into a triangle satisfying that all triangles are integral and pairwise similar . count the number of different approaches to form triangles. Two approaches are considered different if they produce different numbers of triangles, and/or there exists i that the i -th (again, pieces are ordered) triangle in one approaches is not congruent to i th triangle in another plan. Since the answer can be very large, output the answer modules 1000000007. Solve this problem by at most 0.5 KB of source code. Input Each test case consists of one line containing one integer n (1 ≤ n ≤ 5,000,000). Process until EOF is reached. Output For each test case, output one line. See the example for more format details. Example Input: 1 2 3 4 5 6 8 9 10 11 12 15 19 20 100 1000 Output: Case 1: 0 Case 2: 0 Case 3: 1 Case 4: 0 Case 5: 1 Case 6: 2 Case 7: 1 Case 8: 6 Case 9: 3 Case 10: 4 Case 11: 10 Case 12: 25 Case 13: 10 Case 14: 16 Case 15: 525236 Case 16: 523080925 Explanation A triangle is integral when all sides are integer. Two triangles are congruent when all corresponding sides and interior angles are equal. Two triangles are similar if they have the same shape. For n = 9, there are 6 different ways: (1,1,1) * 3; (1,1,1), (2,2,2); (2,2,2), (1,1,1); (1,4,4); (2,3,4); (3,3,3).
33,007
Graph (GRAPH2) Given an undirected graph with n nodes and m weighted edges, every node having one of two colors - black (denoted as 0) and white (denoted as 1). You are to perform q operations of two kinds: C x: Change the x -th node´s color. A black node should be changed into a white node, and vice versa. Q A B: Find the sum of weight of edges whose two end points of color A and B. A and B can be either 0 or 1. Input The first line contains two integers n (1 ≤ n ≤ 10 5 ) and m (1 ≤ m ≤ 10 5 ) specified above. The second line contains n integers, the i -th of which represents the color of the i -th node, 0 for black and 1 for white. The following m lines represent edges. Each line has three integer u, v and w (1 ≤ u, v ≤ n, u ≠ v), indicating there is an edge of weight w between u and v. w fits into 32-bit signed integer. The next line contains only one integer q (1 ≤ q ≤ 10 5 ), the number of operations. The following q lines - operations mentioned above. See samples for detailed format. Output For each Q query, print one line containing the desired answer. See samples for detailed format. Example Input: 4 3 0 0 0 0 1 2 1 2 3 2 3 4 3 4 Q 0 0 C 2 Q 0 0 Q 0 1 Output: 6 3 3 Input: 4 3 0 1 0 0 1 2 1 2 3 2 3 4 3 4 Q 0 0 C 3 Q 0 0 Q 0 1 Output: 3 0 4 This problem has a somewhat strict source limit and time limit.
33,008
Spy (SPY2) Blue Mary extremely likes making PPTs. She has already made L PPTs. Now the only problem before finish is to set the background pictures for each PPT. She has N background pictures, and each PPT needs exactly one background picture. Different PPTs can use same background pictures. Obviously, there are N L combinations. For each combination, Blue Mary defines its weight as (k+1) -1 , where k is the number of pictures (from the N pictures in total) that do not appear in it. Now Blue Mary wants to calculate the sum of weights of all combinations. (Blue Mary is such a weird girl that she always does some meaningless calculations.) She asks you for help. Input Multiple test cases, the number of them is less than 500. Each test case consists of a single line with two space-separated integers N and L . All input numbers are positive and less than 10 6 . Input terminates by EOF. Input data is almost log-uniform randomly generated. Output For each test case, output the required value in a single line. It's guaranteed that this number is always an integer for all input data. Since it can be quite large, output it modulo 10 9 +2015. (Why not 10 9 +7? Remember Blue Mary is a weird girl!) Example Input: 2 2 Output: 3
33,009
Age of Empires (AGE2) This is the hard version of problem SC1 . "Age of Empires" is a famous real-time strategy game. Resource is one of the most important consideration when playing this game. In this game, there are four different types of resources: food, wood, stone and gold. The Villager is a common civilian unit for almost every game. They are the backbone of all civilizations. The Villagers are arguably the most important units in the game because they are able to collect all the resources. Each villager could gather A1 units of food, or B1 units of wood, or C1 units of stone, or D1 units of gold. Note that the villager can not split one second into smaller pieces to gather different types of resource. For example, a single villager can not gather A1/2 units of food and B1/2 units of wood for a single second. Moreover, all kinds of recourse are gathered exactly the end of that second. Nevertheless, different villagers could gather different types of resources at a time. You can also train more villagers to speed up the process of gathering. To train a villager, you must spend X units of food at the beginning of a second, and a new villager will able to work after T seconds. Please note that at the beginning of the second you start to train a villager, you must have not less than X units of food. All villagers are trained at the Town Center but unfortunately there is only one Town Center, so your can only train one villager at a time. You have N villagers at the beginning of the game with initially no food, wood, stone or gold at all. You are interested in the fastest way to gather enough resources, more precisely, at least A2 units of food and B2 units of wood and C2 units of stone and D2 units of gold. Input Each test case consists of three lines. The first line contains four integers A1, B1, C1 and D1 (1 <= A1, B1, C1, D1 <= 10^18), indicating the amount of resource a villager can gather for each type in a second. The second line also contains four integers A2, B2, C2 and D2 (0 <= A2, B2, C2, D2 <= 10^18), indicating the amount of resource required. The third line contains three integers N, X and T (1 <= N,X,T <= 10^5), indicating that you have N villager at the beginning of the game, and it will spend X units of food and T seconds to train each new villager. All integers are sepearted by single spaces. Process until EOF is reached. Output For each test case, output a integer - the minimum time to gain enough resources. See the example for more format details. Example Input: 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 2 2 2 2 1 1 1 1 1 1 1 10 10 10 10 1 1 25 Output: Case 1: 1 Case 2: 5 Case 3: 34
33,010
Blackjack (BLACJACK) You, as a great mathematician and a former member of Blackjack Team, are recently declared "unwelcome person" by managers of local casinos. Extremely bored, you reminded of your life forming a team beating casinos at blackjack worldwide, and decided to help your friends in winning blackjack games. Blackjack, also known as twenty-one, is a game frequently seen in casinos, played with one deck, or several decks of 52 cards. The version your friend plays is slightly different from what we used to see in usual casinos. In this version, the game is played between a player and a dealer with a deck of n cards, namely a 1 , a 2 ... a n , instead of regular decks of 52 cards in standard version. The i -th card has the unique numeric value a i , which is important in following description of rules. The game is played in several rounds as long as not less than k (k ≥ 10) cards left in the deck. Cards are dealt from a 1 to a n , while each card is dealt out at most once. In each round, the player is dealt one card, then the dealer, then the player, then dealer. They now have two cards in their hand respectively. Then the player would keep on taking a hit until he busts (total value of his hand exceeds 21 points) or he feels it is enough (total value of his hand exceeds 15 points) or he has taken 3 hits already. He immediately loses the round if he busts. If he has taken 3 hits without bust, making his hand consist of 5 cards, he wins the round, ending the round right away. Then the dealer will use the exactly same strategy as the player. Of course, the dealer loses the round immediately if he busts, wins the round at once if his hand consists of 5 cards, with the same rule applying. If after taking hits neither the player nor the dealer wins or loses, sums of points (described below) in their hands will be compared, and the person with larger one will win the round. In case of tie, neither wins or loses. Of course, this ends the current round. In the casino your friend plays, there is a special rule: before the game starts, the player is required to cut the deck of card exactly once. By saying cut the deck we mean to change deck of cards from a 1 , a 2 ... a n to a p , a p+1 ... a q , a 1 , a 2 ... a p-1 , a q+1 ... a n (1 < p ≤ q < n) With your super power (in hacking) you now know the deck of cards to play. Now you want to instruct your friend to cut the cards by telling your friend p and q in a secret manner, in order to maximize number of rounds he wins. Input There are several test cases, the number of them is about 15. For each test case, the first line contains two integers, namely n (20 ≤ n ≤ 2000) and k (10 ≤ k ≤ n). The following lines contain totally n characters separated by spaces or line breaks. Characters can be any of A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K where A stands for numeric 1 and T, J, Q, K stands for numeric 10. Input is terminated by EOF. Output For each test case, output one line "Case X: Y" where X is the test case number (starting from 1) and Y is a number indicating the desired answer. Example Input: 20 10 8 4 7 8 8 K 5 A Q Q A Q 6 4 J 6 9 5 3 9 40 10 3 J 7 7 2 T J 6 A 4 4 8 J T 6 A 6 2 K 9 6 5 7 J T 3 5 5 3 7 7 J 5 3 A 5 9 Q 6 7 Output: Case 1: 3 Case 2: 6
33,011
Recursive Sequence (Version X) (SPP2) Sequence (a i ) of natural numbers is defined as follows: a i = b i (for i <= m ) a i = c 1 a i-1 + c 2 a i-2 + ... + c t a i-t (for i > t ) where b j and c j are given natural numbers. Your task is to compute a n and output it modulo 10 9 +7. The above is the description of the original problem SEQ . However, to be a problem in a regional contest, the description will be slightly modified to make the problem a little bit complicated: for almost all integers i > m , a i follows the formula given above, but there are q exceptions n 1 , n 2 , ..., n q : a n i = d i1 a n i -1 + d i2 a n i -2 + ... + d it i a n i -t i (for 1 <= i <= q ) Input For each test case, the first line contains three integers n ( m < n <= 10 9 ), m (1 <= m <= 100), q (0 <= q <= 100). The second line contains m integers b 1 , b 2 , ..., b m . The following line contains several integers, first comes t (t ≤ 100), then t integers c 1 , c 2 , ..., c t . The following q lines describe q special cases of the recurrent formula, each containing several integers, namely n i , t i (t i ≤ 100, t i < n i ), d i1 , d i2 , ..., d it i , as mentioned earlier. It is satisfied that all n i are distinct. All integers are non-negative. Unless specified, all integers are not greater than 10 9 . Input is terminated by EOF. You might assume that all given data is correct. That is to say, all the required numbers can be fixed uniquely by the given input data. Output For each test case output the answer in a single line. Refer to the example for more format details. Example Input: 7 5 0 1 1 2 3 5 2 1 1 10 5 1 1 1 2 3 5 2 1 1 10 2 1 2 Output: Case 1: 13 Case 2: 76
33,012
Yet-Yet Another Counting Problem (TREEII) Count the number of rooted trees with n nodes, which satiesfy the following condition: If the distance between node A and the root equals to the distance between node B and the root, then A and B must have same number of (direct) children. Two trees are considered identical if and only if there's a bijection of n nodes which transforms one tree into another one. Since the answer can be very large, output the answer modules 1000000007. Input Each test case consists of one line containing one integer n (1<=n<=1000). Process until EOF is reached. Output For each test case, output one line. See the example for more format details. Example Input: 1 2 3 40 50 600 700 Output: Case 1: 1 Case 2: 1 Case 3: 2 Case 4: 924 Case 5: 1998 Case 6: 315478277 Case 7: 825219749
33,013
Yet Another Mathematical Problem (MATHII) Calculate the number of ordered triples of positive integers ( a , b , c ) such that their multiple abc is not larger than a given integer N (1 ≤ N ≤ 10 11 ). Input Each test case contains a single line - N . Input terminates by EOF. Output For each test case output its case number (starting from 1) and the answer in a single line. Example Input: 1 3 6 10 15 21 28 Output: Case 1: 1 Case 2: 7 Case 3: 25 Case 4: 53 Case 5: 95 Case 6: 161 Case 7: 246
33,014
Yet Another Multiple Problem (MULTII) Given a positive integer N (1 <= N <= 10000) and some digits, find the smallest positive multiple of N whose decimal notation does not contain any of the given digits. Input Each test case contains two lines. The first line contains two integers N and m separated by a single space. The second line contains m digits separated by spaces. Input terminates by EOF. Output For each test case output its case number (starting from 1) and the answer in a single line, or "-1" (without quotes) if the answer doesn't exist. Example Input: 2345 3 7 8 9 100 1 0 Output: Case 1: 2345 Case 2: -1
33,015
Print Big Binary Numbers (PBBN2) Some answers for some problems could be huge binary numbers. In order to check the computation, one could ask you the sum of its digits. With a little base, the answer is a small number too, but not with a bigger base. XerK would like to avoid precomputed results and wish check you've computed his huge numbers. Here's a problem that check computation of a big number N. A tutorial edition exists without language restrictions. Let define the function CHK(N, B): Input : N a big number in binary representation, B a power of two. Consider N as a base B number. Output : the sum of its digits in this base. Example :with B=2^8, 12345678 = 78 + 97*B + 188*B*B, so CHK(12345678, B) = 78 + 97 + 188 This should be easily computed with few bitwise-AND, bitshifts and additions. Input The input begins with the number T of test cases in a single line. In each of the next T lines there are four integers A, B, C, D, given in base 10. Output For each test case : * compute N = (A^B) XOR (C^D). * print CHK(N, 2^16384) as a base 10 number. (^ denote the power, and XOR the bitwise operator) Example Input: 2 7 3 5 4 1234 5678 9012 4444 Output: 806 1194204158794232147799<...snip...>9938532444216215551948305 Explanations For test case 1: 7^3 = 343, 5^4 = 625, 343 XOR 625 = 806, CHK(806, 2^16384) = 806. For test case 2: You have to output all 4933 digits of the result. Constraints 1 < T <= 321 1 < A, B, C, D <= 10^4 Edit 2017-02-11, after compiler update ; new TL.
33,016
Teleport (TPORT) Little Aron has to visit the planets of one system. Imagine that the planets are ordered in line and labeled with the numbers 1 to n . Aron has n - 1 teleports labeled with 1, 2 ... n - 1 . The teleport labeled with t could transmit only once, one human from a planet labeled with m to the planets with label m + t or m - t , if such planet exists. Using a space-stop Aron could go to the planet labeled with k , i.e. he starts his journey from a planet with a label k . For the given n and k you have to find the best way Aron can use the teleports in order to visit as many different planets of the system, as possible. Input First line contains two integers n and k (1 ≤ k ≤ n ≤ 1 000 000). Output Output should contain indices t , of the teleports that Aron used, in the order in which he used them. Moreover you have to output t if he used the teleport to jump from a planet with the smaller number to a planet with a higher, and -t if he jumped from a planet with a higher number to a planet with a smaller number. If there are several solutions with the same number of teleports, you can output any one of them. Example Input : 6 2 Output: 4 -5 3 -1 2 NOTE - A simpler version of this task appeared on ITI 2012, Shumen.
33,017
Nlogonian Tickets (NTICKETS) You live in Nlogonia, a country that has N cities connected by some bidirectional roads (as usual). In Nlogonia, there is exactly one path between any pair of cities. You can't use the roads during your travels for free. There is an officer at each road that will let you use it only if you show him a certain number of tickets. If you don't have the required amount of tickets, you just can't use that road. The officer will not keep the tickets, though. You need to show the tickets to him, but you can keep them after that. This indicates that you can use the same ticket in more than one road, if you want to. You are given a description of the road system of Nlogonia and a number of queries. For each query, find the minimum number of tickets you must have to go from a city A to a city B. Consider that city A is the only place where you can buy tickets, so you must be holding all the tickets you will need during the travel before leaving city A. Input Each test case starts with a line containing the integer N (2 ≤ N ≤ 10 5 ), the number of cities in Nlogonia. The cities are numbered from 1 to N. Each of the next N-1 lines contains the description of a road, A B T (1 ≤ A, B ≤ N, A ≠ B, T ≤ 10 9 ), indicating that there's a road between the cities A and B, and you must show T tickets to use it. It's guaranteed that no pair of cities will appear more than once in the input. The next line contains the integer Q (1 ≤ Q ≤ 5×10 5 ), the number of queries. Each of the next Q lines contains two city numbers A B (1 ≤ A, B ≤ N, A ≠ B). The last test case is followed by a line containing the number 0. Output For each query A B, print the minimum number of tickets needed during the travel from city A to city B. Print a blank line after each test case. Example Input: 6 1 2 1 1 3 5 3 4 3 3 5 8 1 6 2 3 2 6 5 2 4 6 0 Output: 2 8 5
33,018
Sheep (KOZE) Mirko has a herd of sheep, surrounded by fences backyard. While he was asleep, wolves have sneaked into the fenced area and attacked the sheep. Backyard is of a rectangular shape, and consists of fields arranged in rows and columns. Character ' . ' (full stop) represents a blank field. Character ' # ' represents a fence. Character ' k ' represents a sheep. Character ' v ' represents a wolf. Two fields belong to the same sector if we can move from the field A to the field B without going over the fence, by making only horizontal and vertical steps (we cannot move diagonally). If we can escape from field A from the backyard, that field does not belong to any sector. Luckily, Mirko taught his sheep Kung-Fu skills, and they can defend themselves against wolves only if they outnumber the wolves in that sector . When there are more sheep in the sector than wolves, all wolves die without sheep casualties. Otherwise all sheep perish and wolves are unharmed. If a field doesn't belong in any sector, sheep will flee and wolfs will be left without a prey, so every animal survives. Write a program that will determine how many sheep and wolves will survive this bloody night. Input Integers N and M, number of rows and columns which represent Mirko's backyard. In every of the N lines, there are M characters representing the appearance of Mirko's backyard - positions of the fences, wolves and sheep. Constraints 3 ≤ N, M ≤ 250 Output In the first and the only line, print the number of sheep and wolves that will survive. Example Input: 8 8   .######.   #..k...#   #.####.#   #.#v.#.#   #.#.k#k#   #k.##..#   #.v..v.#   .######. Output: 3 1
33,019
Ant Colony Optimization (DCEPCA02) Ants are known to move in groups and in perfect order. However, in our problem the ants can move only in directions Left (L), Right (R), Up (U), Down (D). The place is a rectangular grid. There are 2 types of ants: Type A and Type B. Each ant type has its own queen ant which defines the 2 directions at which their type of ants can reproduce ants. A starting cell is given where one ant of each type is standing (A and B). When the process begins, each type of ant produces 4 ants, 2 ants of their type in the 2 directions (1 ant per direction) specified by their queen ant and 2 ants of the other type in the remaining 2 directions. So if queen ant of type A says LR and queen ant of type B says UD then A ant produces new type A ants at left cell and right cell and new type B ants at up cell and down cell of the original cell. Similarly, type B ant produces 2 new type A ants in left and right cell and 2 new type B ants in up cell and down cell. The ants produced again reproduce more ants at their adjacent cells according to the same directions given by the their queen ant. Reproducing ants at adjacent cells take 1 time unit. You need to find the sum of the minimum time in which type A ant reaches the end point and the minimum time in which type B ant reaches the end point. If any type of ant cannot reach end point, the answer is -1. Constraints T ≤ 10 0 < M ≤ 500 0 < N ≤ 500 0 ≤ SX, EX < M 0 ≤ SY, EY < N Input T denotes the number of test cases. Each test case consists of 4 lines. The first line gives M and N which is the size of the grid. The second line gives starting cell cordinates SX and SY. The third line gives end point cell cordinates EX and EY. The fourth line gives a permutation of LRUD denoting the directions provided by queen ant to move. The first two characters of the string gives the directions of queen ant type A and last two characters gives direction of queen ant type B. Output Print T lines each giving the minimum time in which ant of both types can reach the ending cell for each testcase ie. Find sum of (minimum time at which A type ant reaches end point + minimum time at which B type ant reaches end point.) Example Input: 3 5 5 1 1 3 4 LRUD 2 4 0 2 0 3 RULD 2 4 0 2 1 1 URDL Output: 10 -1 6 Explanation Test Case 1: Minimum time at which a type A ant reaches end point = 5, and minimum time at which a type B ant reaches end point = 5 Test Case 2: B cannot reach end point. Hence answer is -1. Test Case 3: Minimum time at which a type A ant reaches end point = 4, and minimum time at which a type B ant reaches end point = 2
33,020
MAD (DCEPCA10) Penny has started taking mathematics classes and has got better at it. She now wants to challenge Sheldon at this expertise and make a fool out of him. She writes down a list of numbers as list A and calculates the median of it. Then she calculates the absolute deviation of each number from this median value to make list B. Now she finds the median of this list B. She asks Sheldon to find the minimum number of elements he needs to change in list A so that the median of list B becomes equal to 0. Can you help Sheldon do this? For example: List of numbers (A):  4 5 3 1 2 Median of list A = 3 List of Absolute Deviation from median (B) = 1 2 0 2 1 Median of list B = 1 Note: Median of even length list is the mean of 2 middle values. Constraints 0 < T ≤ 10 0 < N ≤ 10 5 0 ≤ A[i] ≤ 10 9 Input T Number of test cases followed 2T lines. First line of test case contains N, size of array. Second line contains A[0] to A[N-1]  the numbers of the array. Output T lines each containing a single number which denotes the minimum number of elements we need to change to get the median of the absolute deviation of numbers from median to be 0. Example Input: 2 5 4 5 3 1 2 10 5 5 5 254 5 5 768 5 5 5 Output: 2 0
33,021
Short Select (DCEPCA04) ICPC has grown very big this year and 100 teams have put in their applications to appear for onsite event. The problem setters were also able to make 44 problems which can be selected for the onsite event. Moreover,  they are very familiar with all the 100 teams and exactly know which team will be able to to solve which problem in the contest. They set a number X which should be the minimum number of total accepted solutions with which they can call the contest to be successful. Help them to find the ways in which they can select 10 problems out of 44 such that the  total number of accepted solutions are greater than or equal to the minimum number set by the judges. Note: There is only one test case. Constraints 0 ≤ X ≤ 10 9 Input First 100 lines contain a binary matrix 100 by 44 which denotes which problem is solved by which team in the contest. I.e. if A[i][j] = 1, it denotes that the ith team can solve jth problem. Next line contains a number X which is the minimum number of accepted solutions that is required by the judges Output Print a number which is the number of ways in which problem setters can select 10 problems out of 44 such that the total number of accepted solutions are greater than or equal to the number X set by them. Example Input: 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 Output: 0
33,022
Good Luck (DCEPCA01) A number is called lucky if it consists of only digits 4 and 7 ie. 4, 7, 44, 47 are lucky numbers while 3, 45, 4478 are not lucky. For a given lucky number the functions F(i) and G(i) are defined as follows F(i) = the number of 4’s from 0 th to i th position in the number including positions 0 and i. G(i) = the number of 7’s from 0 th to i th position in the number including positions 0 and i. Let H(i)= absolute(F(i)-F(i+1)-F(i+2)+F(i+3)) A "Dynamic Number" is a lucky number which has maximum of summation(H(i)) from i = 0 to n-4 amongst all lucky numbers of length N. Given a number N , you need to find out the sum of the two smallest Dynamic Numbers of length N.If only one Dynamic Number is possible, then only that number is the answer. Note : Most significant bit is defined as the 0 th position of the number. Constraints 0 < T <= 100 4 <= N <= 10^5 Input It consists of T+1 lines. T denotes the number of test cases. Followed by T lines, each containing one number N. Output Output T lines, each containing a number as required. Example Input: 1 4 Output: 8924
33,023
Saving BOB - 2 (DCEPCA08) Alice and Bob devised a new game to play. Alice wrote an expression on the paper and started generating an array of numbers from that. She wrote the formula as a[i] = (51 * a[i - 1] + 52) % 53 + 1 The array starts from index 1 and a[0]=1 Bob takes all the numbers from that array up to an index N also given by Alice. He makes all the subsets possible from that array. He calculates the sum of numbers in each of the subsets and finds which of the subset is prime. A subset is prime if the sum of numbers in the subset is a prime number. Bob gets boggled by the enormous size of array that Alice is generating and asking him to do this. Can you help Bob calculate the number of different prime subsets that can be made from the given array ? Constraints 0 < T <= 100 0 < N <= 10^5 Input It consists of T+1 lines were T is the number of test cases and N is the index of the array up to which Bob has to calculate. The array of the numbers can always be formed from the formula that Alice wrote. Note : Array index starts from 1. Hence a[0] is not an element of the array. Output Print T lines each containing the number of different prime subsets that can be made from the array given. Example Input: 2 4 5 Output: 3 6
33,024
Binary Matrix (BNMT) You are given a matrix of size  r x c . Each of the elements can be either 0 or 1.  In each operation you can flip any element of this matrix, i.e. convert 0 to 1 or convert 1 to 0. Your goal is to convert the matrix such that - Each of the rows will have the same number of 1s and Each of the columns will have the same number of 1s. What is the minimum number of operations required to achieve this? Input Input starts with a positive integer  T  (~1000) which indicates the number of inputs. Each case starts with two integers  m  and  n  (1 <= r , c <= 40), here  r  is the number of rows and  c  is the number of columns of the matrix. Each of the next m lines will have n integers each, either 0 or 1. Output For each test case, output “Case #: R” in a single line, where # will be replaced by case number and  R  will be replaced by the minimum number of steps required to achieve the target matrix. Replace  R  by -1 if it is not possible to reach target matrix. Example Sample Input: 3 2 3 111 111 3 3 011 011 011 2 3 001 000 Sample Output: Case 1: 0 Case 2: 3 Case 3: 1
33,025
Saving BOB (DCEPCA06) Alice and Bob start playing a new game. Alice writes 2 numbers - N and K. She asks Bob to find an integer which is N digits long such that the absolute difference in the adjacent digits is greater than or equal to K. Bob realizes that a lot of integers satisfy this condition.  Can you help Bob to find the total number of N digit integers which satisfy the condition set by Alice? Since the answer can be very large, print the answer modulus 1000000007. Note : The adjacent digits to a digit constitute both the left and right neighbor of the digit. Starting from the left, only the second digit is regarded as adjacent to the first digit and only the second last digit is regarded as adjacent to the last digit. Constraints T = 100 2 ≤ N ≤ 10 9 0 ≤ K ≤ 9 Input First line contains T- the number of test cases. The next T lines contains two numbers N and K as given by Alice. Output Print T lines each containing the total number of integers of N digit mod 1000000007 which satisfy the condition set by Alice. Example Input: 2 2 9 2 8   Output: 1 4
33,026
Totient Extreme (DCEPCA03) Given the value of N, you will have to find the value of H. The meaning of H is given in the following code: H=0; For (i=1; i<=n; i++) {     For (j=1; j<=n; j++) {         H = H + totient(i) * totient(j);     } } Totient or phi function, φ(n) is an arithmetic function that counts the number of positive integers less than or equal to n that are relatively prime to n. That is, if n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1 Constraints 0 < T ≤ 50 0 < N ≤ 10 4 Input The first line contains T, the number of test cases. It is followed by T lines each containing a number N . Output For each line of input produce one line of output. This line contains the value of H for the corresponding N. Example Input: 2 3 10 Output: 16 1024
33,027
MMM (DCEPCA09) Everyone knows how to find mean, median and mode of an array of numbers. For people who don’t know this, here is the description: Mean is the arithmetic average of a set of values. Median of a finite list of numbers can be found by arranging all the observations from lowest value to highest value and picking the middle one. If there is an even number of observations, then there is no single middle value; the median is then usually defined to be the mean of the two middle values. The mode is the value that appears most often in a set of data. If more than one number is applicable to be the mode, select the highest value number amongst them as the mode. The problem is just to find these 3 values. Given an array of numbers and two indices i and j, find the mean, median and mode of elements in the interval i to j including numbers at indices i and j. Note that i and j are 0 index based. Constraints 2 ≤ N ≤ 10000 1 ≤ Q ≤ 10000 0 ≤ A[i] ≤ 10 8 0 ≤ i < N i ≤ j < N Input First line contains N which is the total number of numbers in the array. The next line contains N numbers A[i] which are the elements of the array. Next line contains a number Q which defines the total number of queries we are making for the interval i to j. It is followed by Q lines each containing 2 numbers i and j which denotes the indices to be queried for. Output Print Q lines each containing 3 numbers Mean, Median and Mode respectively. If the answer for any case comes to be a floating point, then take the integer part of the number as the answer. For example: if mean, median and mode comes up to be 6.44 7.8 9 then the final answer is 6 7 9. Example Input: 5 6 5 3 7 7 2 1 2 0 4 Output: 4 4 5 5 6 7
33,028
n-divisors (NDIV) We all know about prime numbers, prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We can classify the numbers by its number of divisors, as n-divisors-numbers, for example number 1 is 1-divisor number, number 4 is 3-divisors-number... etc. Note : All prime numbers are 2-divisors numbers. Example: 8 is a 4-divisors-number [1, 2, 4, 8]. Input Three integers a, b, n. Output Print single line the number of n-divisors numbers between a and b inclusive. Example Input: 1 7 2 Output: 4 Constraints 1 <= a, b <=10^9 0 <= b - a <= 10^4 1 <= n <= 100
33,029
Counting (RIOI_3_2) Given integers N and M , output in how many ways you can take N distinct positive integers such that sum of those integers is <= M . Since the result can be huge, output it modulo 1000000007 (10^9 + 7) N <= 20  M <= 100000 Input First line of input is number t , number of test cases. Each test case consists only of 2 numbers N and M, in that order. Output Output the answer asked for in the description. Example Input: 4 6 16 4 16 1 14 3 7 Output: 0 27 14 2
33,030
Another Gift Problem (VPL0_A) Luis is becoming mad because his family hid all the Christmas gift in the family’s apartment, as his family is wealthy, they own a giant skyscraper that has many floors. By using the elevators, he wants to find all the gifts. Luis’ parents went out and this is the perfect opportunity he has to sneak and view the Christmas gifts before Christmas eve! Luis earned a map of the building and marked the places where he can find the gifts. An elevator of the building can only go up and go down, now, you can assume that the elevators will always be on any floor and will be able to take it, however, the elevator takes one unit of time to bring Luis to any floor Ai, Luis should never leave the building at any moment using the elevators. When Luis gets to any floor, he will start seeking the gift from the position (0, 0), after seeing all the room he will return to the elevator and keep his way. his searching ends when he finds all the gifts. Luis can ignore places that aren’t marked, so for example, if he knows that in a floor Fi there is no gifts, he can continue his way through the elevators. You can assume some things about Luis’ skyscraper building. He lives on the first floor of the skyscraper (floor 0, position 0, 0). Luis must be in each floor in the position (0, 0) in order to use an elevator. There will no gifts in his floor, because his parents try to hide it from him. He will never leave the building at any moment using elevators. Every floor of the skyscraper is perfectly the same one from another and can be represented as a NxN matrix. The elevators will be always available and can go up or down, never both. (You can assume that the elevators will be always moving). The coordinates of the gift are unique, that is, you can safely assume that no gift will overlap another one. Luis can only walk in a floor from point (a, b) through point (c, d) going into vertical and horizontal directions, that is, for each unit of time, he can move north, east, west or south. The transition from one elevator to another takes one unit of time, the time inside the elevator is immediate. Finally, knowing the number of floors, the number of elevators and their values, the number of gifts and the position of each gift, and then the size NxN of every floor in the apartment, determine the minimum time that Luis can delay checking all his gifts and returning to the point 0, 0 on the last gift's floor after he sees the last one. It is guaranteed that a solution will always exist. Input The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases. Four integers will begin every test case: M, E, K and N, denoting, respectively, the number of floors, the number of elevators, the number of gifts and the size for every floor in the skyscraper. Then, E lines will follow, meaning that the i-th elevator goes ”up” Ei floors. (If the number is negative, then it goes down Ei floors. After that, K lines will follow, each one of them with three integers denoting that the i-th gift is on floor f at the position (r, c). Output For each input case you must print the string "Scenario #i: " where i represent the case you’re analyzing (starting from 1), followed by the minimum units of time that takes Luis to check all the gifts. Sample Input: 5 5 1 1 1 1 3 0 0 5 3 1 1 1 4 -1 3 0 0 5 1 2 1 1 2 0 0 4 0 0 10 3 2 1 1 8 -2 4 0 0 6 0 0 5 3 3 5 1 2 -1 2 1 3 2 4 1 2 3 4 Output: Scenario #1: 3 Scenario #2: 2 Scenario #3: 4 Scenario #4: 3 Scenario #5: 17 Explanation of the last case Luis starts in floor 0, takes an elevator to floor 2, lets call the three gift on the second floor (A, B, C) with A = {1, 3}, B = {4, 1}, C = {3, 4}, he can pick the gifts in several ways; A, B, C; B, C, A; C, A, B; C, B, A; A, C, B; B, A, C; However, the minimal combination is B, A, C and return to the origin (0, 0) that is 16 steps used plus the unit of time in the elevator, total = 17. 1 ≤ T ≤ 10 Subtask 1 - 5% 2 ≤ M ≤ 100 1 ≤ E ≤ 1 1 ≤ K ≤ 1 1 ≤ N ≤ 1 You can assume that the gift will be at the origin point (0, 0). Subtask 2 - 5% 2 ≤ M ≤ 1,000 1 ≤ E ≤ 10 1 ≤ K ≤ 10 1 ≤ N ≤ 1 You can assume that the gift will be at the origin point (0, 0). Subtask 3 - 10% 2 ≤ M ≤ 100 1 ≤ E ≤ 10 1 ≤ K ≤ 1 2 ≤ N ≤ 100 Subtask 4 - 10% 2 ≤ M ≤ 1,000 1 ≤ E ≤ 100 1 ≤ K ≤ 1 2 ≤ N ≤ 1,000 Subtask 5 - 20% 2 ≤ M ≤ 1,000 1 ≤ E ≤ 20 1 ≤ K ≤ 10 2 ≤ N ≤ 100 It is guaranteed that all the gift will be on different floors. Subtask 6 - 20% 1 ≤ M ≤ 1,000 1 ≤ E ≤ 100 1 ≤ K ≤ 10 1 ≤ N ≤ 1,000 Subtask 7 - 30% 1 ≤ M ≤ 1,000 1 ≤ E ≤ 100 1 ≤ K ≤ 10 1 ≤ N ≤ 1,000,000
33,031
Basic Grapes Instinct (VPL0_B) Dickie is cropping grapes for Christmas! He’s very excited about the traditional grape eating race on December 31th, so he picked every possible raceme of grape in his farm and collect them in a big bucket. Nevertheless, he’s having a serious problems ordering the racemes because there are so many of them! In order to organize in a efficient way the humongous amount of grape racemes, he decided to build a stemplot out of them. A stemplot goes as follows: The input values for a stemplot are a sequence of numbers and a stem unit. Data is classified based on the stem value, i.e., if a number in the sequence is 403 and the stem unit is 100, then this number is classified in the category 4. For each category, a list of leaf values are render in a single line, sorted in increasing order. Stem values and leaves are separated by a | (pipe character). All | should be vertically aligned. Stem values are sorted in increasing order, omitting empty stems. Given the sequence s = { 44 46 47 49 63 64 66 68 68 72 72 75 76 81 84 88 106 }, the stemplot generated with a stem unit of 10 is rendered as follow: 4 | 4 6 7 9 6 | 3 4 6 8 8 7 | 2 2 5 6 8 | 1 4 8 10 | 6 Dickie is having big trouble rendering these stemplots of grape racemes, can you do the job for him and save the traditional grape race of December 31th? Input The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases. The first line of each case will contain 2 integers N and U, indicating the size of the sequence and the stem unit. Next N lines will contain a single element of the sequence s i . Output For each case you should print the string "Scenario #i:" where i is the test case you are evaluating (starting from 1), a new line, and then the corresponding stemplot following the rules stated above. Print a blank line after each stemplot. Sample Input 2 17 10 44 46 47 49 63 64 66 68 68 72 72 75 76 81 84 88 106 5 23 1 9 127 23 73 Output Scenario #1:  4 | 4 6 7 9  6 | 3 4 6 8 8  7 | 2 2 5 6  8 | 1 4 8 10 | 6 Scenario #2: 0 | 1 9 1 | 0 3 | 4 5 | 12 Subtask 1 - 30% 1 ≤ T ≤ 100 1 ≤ N ≤ 100 1 ≤ U ≤ 100 1 ≤ si ≤ 1,000 Subtask 2 - 70% 1 ≤ T ≤ 100 1 ≤ N ≤ 10,000 1 ≤ U ≤ 1,000 1 ≤ si ≤ 1,000
33,032
Collision on Christmas Eve (VPL0_C) Danny is preparing to receive his Christmas gift, their parents said that it is a very awesome gift and Danny could not think on anything else than what is inside the box. Weeks ago, the parents of Danny gave him a homework that Danny didn’t complete because it was too boring for him, but suddenly, at December 25th, the parents are asking Danny to give the answer of his homework! Danny is falling into desperation and requires your help. Now, before giving the Christmas gift, the parents asked Danny for the homework, and it goes like this: given two numbers N and K, find the number with the largest quantity of divisors following the progression: A 0 =1, A 1 =A 0 +K+1, A 2 =A 1 +K+2, and so on. The value of A n  should not exceed the number N given. Input The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases. Each case contains only two numbers N and K, giving the maximum number to evaluate and the value of the progression’s constant. The input must be read from standard input. Output For each input case you must print the string "Scenario #i: " where i is the test case you’re analyzing (starting by 1), followed by the number who contains the largest quantity of divisors in it with the number of divisors associated, in case of a tie, choose the smaller. The output must be written to standard output. Example Input: 4 4 0 28 1 2 2 78 3 Output: Scenario #1: 4 3 Scenario #2: 28 6 Scenario #3: 1 1 Scenario #4: 40 8 Subtask 1 - 20% 1 ≤ N ≤ 1,000 10 ≤ K ≤ 100 Subtask 2 - 30% 1 ≤ N ≤ 100,000 0 ≤ K ≤ 100 Subtask 3 - 50% 1 ≤ N ≤ 10,000,000 0 ≤ K ≤ 100
33,033
Drastic Grapes (VPL0_D) It’s December 31st. New Year’s Eve. Lino and his family are waiting to eat grapes as part of one Venezuelan tradition to ask for wishes to become the New Year. Lino’s parents do it because of the tradition while his little sister Shouri gives a priority to each wish according to its importance, If she has a wish with P priority she must eat a grape with P power, however, the grapes are on the table and she is not tall enough to take them and she gives Lino a list of size N with her priorities. In addition, Lino has another list of size M given by his mother with a brief description of the grapes on the table. Grapes have different characteristics and Lino’s mission is to maximized Shouri’s wishes but with some restrictions: Lino only takes grapes with the same priorities and power. Lino can only take the i-th grape on the table if and only if the grapes taken before and the new one are in the same order in both lists, in other words, if there is on the list of priorities {5, 4, 1, 3, 2} and the grapes on the table are {7, 1, 5, 4, 9, 3, 2, 1, 2, 0}, he can choose {4, 2} or {4, 3, 2} but never {1, 4} or {1, 2, 3, 4} if Lino can choose between grapes {1, 2, 3} and {4, 5} he choose the ones with the maximum power {4, 5} if Lino encounters two groups of grapes with the same power, he will choose the biggest group, example, between {4, 5} and {3, 3, 3} he will choose {3, 3, 3}. Input The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases. Each line contains two integers K and N, denoting, respectively, the list of grapes that Shouri holds and the grapes that are on the table. After that, follows a line containing K integers with the description previously mentioned and another line with N integers with the description mentioned too. The input must be read from standard input. Output For each input case you must print the string "Scenario #i: " where i denotes the test case you are evaluating (starting by 1) followed by two numbers, each one denoting the maximum power achievable and the number of grapes to be taken. If there are no group that can satisfy Shouri’s needs, then print 0 0 as maximum power and maximum number of grapes. The output must be written to standard output. Sample Input 3 3 3 1 2 3 3 2 1 3 3 2 4 5 3 2 5 5 7 3 3 3 4 5 4 5 3 8 3 12 3 Output Scenario #1: 3 1 Scenario #2: 7 2 Scenario #3: 9 3 Subtask 1 - 20% 1 ≤ T ≤ 100 1 ≤ K ≤ N 1 ≤ N ≤ 15 Subtask 2 - 30% 1 ≤ T ≤ 100 1 ≤ K ≤ N 1 ≤ N ≤ 100 Subtask 3 - 50% 1 ≤ T ≤ 20 1 ≤ K ≤ N 1 ≤ N ≤ 1000
33,034
Count on a treap (COT5) In computer science, a treap is a binary search tree according to the keys and meanwhile a heap according to the weights. Your task is to maintain a max-treap supporting the following operations: 0 k w : Insert a new node, whose key and weight are k and w . 1 k : Delete a node in the treap with key k . 2 ku kv : Return the distance between node  u whose key is ku and node  v whose key is kv . No two nodes share a same key or same weight, and we guarantee the node is indeed in the treap before a delete operation takes place. Input The first line contains an integer N (1 ≤  N ≤ 200000), the number of operations. The next N lines each contains two or three integers "0 k w ", "1 k " or "2 ku kv " (0 < k ,  w ,  ku ,  kv ≤ maxlongint). Output For each query operation, print the distance between u and v . Example Input: 12 0 4 17535 0 10 38964 0 2 21626 0 1 61321 2 1 10 2 10 4 1 10 1 1 0 8 42634 2 8 4 2 8 2 2 4 2 Output: 1 2 2 1 1
33,035
To inifinity and Beyond (BUZZ) You probably don't know toys walk, play and talk when we are not around. And there are toys who can perform intergalactic missions! But lets forget about alien planets now, the toy-land on earth is in danger, “Zurg” the evil emperor from outer world is planning to capture it. But as always when toyland is in trouble the great space ranger “Buzz Lightyear” of star command comes for the rescue! Toyland consists of several cities and bidirectional roads. The Toyland chief wants to take following steps to save Toyland: First divide the cities of Toyland into multiple regions. Two cities MUST be included in same region if there is at least one cyclic route connecting both cities. One city can be included in multiple regions. Size of each region should be maximal, that means extra city can't be added in a region. There are limited number of “Buzz” toys available. After creating the regions, one “Buzz” toy will be sent to each of them to save that region from Zurg! Toys need energy. Each city can supply energy to infinite number of toys but the amount of energy a city provides daily to a single toy is limited otherwise toys may waste energy. A toy is assigned to a single region but it can get energy from any city with in its region. For a single toy, the total daily energy supply is sum of the energy supply of all the cities within its region. Each “Buzz” may need different amount of energy to work. If a region provides too little energy than additional energy need to be provided anyhow and it is considered as a loss. But if the region provides more energy than required, “Buzz” wastes it by playing with laser and flying all around. So: Daily Loss in region X = | Daily Energy required by “Buzz” assigned in that region - Daily Energy supplied by region X | Exactly one “Buzz” must be assigned in each region, if there are more toy than needed, they'll keep them for emergency. The chief wants to minimize the maximum wastage among all the regions and he needs your help desperately. Help the toyland to survive, expand your mind To Infinity and Beyond and find the answer. Input Input consists of several files. First line of each file will consist the number of test cases (T <= 101). For each case, first line will consists number of cities (1 <= N <= 251), roads (E >= 0) and number of Buzz toys available (1 <= B <= 251). In next line there are N integers less than 1000, i-th integer denotes energy supply in city i. In next line there are B integers less than 1000, j th integer denotes energy required by Buzz j. Next there are E lines each consisting two integer u and v denoting there is a bidirectional road between u and v (u != v). There are at most one roads between two cities. All inputs are non-negative. Output First print number of regions. Than if number of regions is more than number of buzz available, output “No”. Otherwise print the maximum wastage amount among all the regions. Dont print any extra spaces or newlines. Print case number for every case, see sample output for details. Sample Input: 2 6 7 3 5 4 8 1 2 6 10 14 9 1 2 2 3 3 1 3 4 4 5 3 5 5 6 4 3 1 5 4 8 1 10 1 2 2 3 3 1 Output: Buzz Mission 1: 3 3 Buzz Mission 2: 2 No Large input File, use faster I/O.
33,036
SHAPE GAME (SGAME) You probably might have played the game of constructing a figure without lifting up the pencil. But it seems too easy for us. Let's add some twist to it! What about start constructing a figure from a point and returning to the same point resulting in the figure without lifting up the pencil. Note: Figure is bounded and one can't retrace an arc or line. INPUT SPECIFICATION Input consists of several test data. There are 't' test cases. For each case you are given the point index 'n' from which to start and end. Then follows two space separated index that define a line from index 'i' to index 'j'. These integers follow up until "-1 -1" is encountered. OUTPUT SPECIFICATION Output "YES", if it's possible to construct figure satisfying the specification and "NO" if it's not possible (without quotes). CONSTRAINTS t<=100 1<=n<=300 1<=i,j<=300 i!=j EXAMPLE Sample Input: 1 1 1 2 1 4 2 3 2 5 2 6 3 6 4 7 5 6 6 7 -1 -1 Sample Output: YES
33,037
Fences (CEOI08A) One morning, fruit farmer Fred visits his apple trees and notices that one of them was cut overnight. This means a loss of 111e – the money he can make from the apples of a tree on average. In order to prevent further losses, he decides to erect a fence on his plantation. The fence consists of posts connected by wire. The fence posts can only be placed at a given set of pre-drilled holes. While Fred can get wire for free, he needs to buy the fence posts for 20e each. So it might not always be worth or even possible to fence in all of his trees. The plantation is square and 1 000 × 1 000 m 2 large. In bird’s eye view, the lower left corner has coordinates (0, 0), the upper right (1 000, 1 000). In this example there are four pre-drilled holes (circles) and three trees (squares). It is optimal to buy three fence posts and put them into selected holes (filled circles), to connect them by wire (lines), and to leave the upper left hole empty. The cost of erecting the fence is 3 × 20e + 1 × 111e = 171e since three posts were bought and one tree could not be fenced in (which means a loss of that tree’s harvest). Write a program that reads the positions of the pre-drilled holes and the trees on Fred’s plan-tation and outputs the minimum cost of erecting a fence or erecting no fence at all. You can neglect the actual shape of the trees and calculate with their positions only. Input The first line contains two integers N and M (3 ≤ N ≤ 100, 1 ≤ M ≤ 100). N is the number of pre-drilled holes, and M is the number of trees. This line is followed by N lines that describe the positions of the holes, and then by M lines that describe the positions of the trees. Allpositions are given as pairs of integers x y on one line (0 ≤ x, y ≤ 1 000). You can expect that no two positions (of holes and trees) coincide and that no three positions are colinear. Output Output a single line containing one integer: Fred’s minimum cost. In case Fred buys P posts and fails to fence in T trees, his cost are 20 × P + 111 × T. Example Input: 4 3 800 300 200 200 200 700 600 700 400 300 600 500 800 900 Output: 171 This example corresponds to the picture above. (Official Test Data)
33,038
For Loops Challenge (PFORLOOP) Bjarne is learning about programming. Yesterday’s lesson was about for loops. To put his skills into practice, he had to write a number of for loops that printed consecutive positive integers. He was so proud of his creation that he stored the output of his program into a file. For example, the contents of the file could have looked like this: 5 6 7 8 9 10 11 12 13 14 56 57 58 59 60 61 62 63 64 65 100 101 102 103 104 105 106 Today, he opened his file and realized it is now inconsistent: the numbers weren’t sorted in ascending order anymore! His wife told him she was bored so she swapped some numbers around. He’s so frustrated he can’t rewrite the program. Your task is to help him out. Read out the numbers and print all the C++ for loops that recreate the original file. Input There are many lines in the input. The i-th line contains a sequence of space-separated positive integers, where each integer is between 0 and 1000000000. It is guaranteed there are no repeated integers and that there will be at minimum one line with one integer, no line will have more than 1000 integers. Output Output all the for loops that generate Bjarne’s original file, one per line. Print the for loops in  order. That is, if the numbers of the i-th loop are less than the numbers of the j-th loop, the i-th for loop must be printed first. Notes Name ‘i’ the variable of each for loop. Don’t use brackets. The for loop condition must be inclusive, that is, use ‘<=’. The increment section of the for loop must be "i++". The C++ code you print need not include a line ending command. Beware of spaces. All your for loops must contain the same number of spaces as this sample: for (int i = a; i <= b; i++) cout << i << " "; Example Input 9 6 100 1 3 105 2 4 101 102 103 104 5 7 8 Output for (int i = 1; i <= 9; i++) cout << i << " "; for (int i = 100; i <= 105; i++) cout << i << " ";
33,039
Easy Programming Tutorials (EPTT) The ACM-ICPC movement has become very strong in the Dominican Republic and many students are now looking for specialized programming classes to tackle their specific needs. You work at a top school that has produced many world-class programmers. These programmers have a lot of time to spare and would like to tutor as many students as possible so as to continue producing more world-class programmers. Nonetheless, you have a very limited budget and thus want to minimize costs. Every day you receive a number of requests from students where each request Ri has a start time Si. Each tutorial lesson lasts exactly 30 minutes. Luckily, you always have more tutors than requests. On any day, however, tutors are constrained to work only one stretch of at most two hours and each can only service one request at a time. For example, if there is a request coming in at time 0 and another one coming in at time 31, you would need two tutors to service both. If instead the second one comes at time 30, you would then need only one tutor. Given a list of requests for a day, compute the minimum number of tutors necessary to serve them all. Input The first line contains a single integer R (1 ≤ R ≤ 1,000,000), the number of requests for the day. Then there are R lines. Each line contains the i-th request. Each request is represented by its integer start time in the range [0, 1410]. Thus the input has in total 1 + R lines. Output The output is a single integer representing the minimum number of tutors needed to serve all requests for the day. Sample Input: 5 0 0 30 60 61 Output: 3
33,040
Counting Primes (CNTPRIME) Tortoise and Achilles are playing the Counting the Primes game. Achilles will give Tortoise some numbers, and some intervals, and then Tortoise needs to count the primes on those intervals. It is an easy game, but Tortoise is doing the counting slowly. Achilles is pissed off, so he has given you the task as you are a good programmer. For a twist, he has changed the game a little bit, that is he will give some intervals for counting the prime as well as he will give some intervals to change the numbers in that interval. You are given an array of n elements. After that you will be given M commands. They are: 0 x y v - you have to change all numbers in the range of x to y (inclusive) to v , where x and y are two indexes of the array. 1 x y - output a line containing a single integer which is the number of primes between x and y (inclusive). The array is indexed from 1 to n . Input Input starts with an integer T (≤ 10) , denoting the number of test cases. Each case contains two integers n (1 ≤ n ≤ 10 4 ) and q (1 ≤ q ≤ 2×10 4 ) . Then next line, you will be given N integers. After that each of the next q lines will contain a task in one of the following form: 0 x y v (1 ≤ x ≤ y ≤ n, 2 ≤ v ≤ 10 6 ) 1 x y (1 ≤ x ≤ y ≤ n) And the numbers will be in range of [2, 10 6 ] . Output For each case, print the case number first. Then for each query '1 x y' , print the number of primes between x and y [inclusively] . Example Input: 1 5 3 78 2 13 12 3 1 1 2 0 4 4 5 1 1 5 Output: Case 1: 1 4 Note: Use Faster IO like scanf, printf A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first prime numbers are 2, 3, 5, 7, 11 ...
33,041
Help MR BEAN (BEANGAME) Mr. Bean loves to play games. For this he wastes lots of money so Mrs. Bean made a hurdle game for him. Now in the game we have 3 tracks and for moving up to next level he will have to cross some hurdles. Each time he changes the track he gets some drink to increase his energy level by that amount. The drink that he gets is the one which is in between the present track and the adjacent track and in the direction of movement (adjacent track may or may not be the track on which he is targeting to move). Now if at any moment his energy becomes negative his game will be over. So you have make him win this game with maximum energy being available with him at last. He will move in the form of 'L' and 'R' between adjacent tracks with 'L' making him move one step left of the present position and 'R' moving him right. Movement between different level will be separated by '-' and if there is no change of track between adjacent levels then print 'U' at its corresponding move . Input First line will have 3 integers Il, Ie, Ns where Il is the initial track on which he is standing, Ie is the initial energy he is having and Ns is the number of levels in the game. Then it would be followed by 5 lines where the first three will have the values of the hurdles present at each level on each track. Fourth line will have Ns-1 integers representing the energy obtained by him on drinking the energy drink between continuous levels between track 1 and 2 and similarly fifth line will have Ns-1 values for drinks between tracks 2 and 3. Output Print "DONE IT!" in first line and the steps taken by him in second line following the path which leads to maximum energy available with Mr. Bean beyond final track. If it is not possible print "GAME OVER!". Constraints Every integer, intermediate values will fit in 32-bit integer. Example Input: 1 6 5 3 2 9 16 3 4 0 7 26 1 1 7 3 30 9 8 19 8 3 10 3 6 4 Output: DONE IT! RR-LL-RR-LL-R
33,042
Vision Field (VISION) There are N buildings stand along the horizon line. Each building are represented as a vertical segment with two end points at (i, 0) and (i, Ai). There are M queries in total. For each query, we wonder know how many buildings you can see if you stand at (0, h). ... N, M ≤ 10 6 , both Ai and h is positive integer and ≤ 10 9 . Input N A1 A2 ... An M (here following the M queries.) Output For each query, simply print how many buildings you can see. Example Input: 5 2 3 3 3 4 3 3 2 4 Output: 3 2 5
33,043
The Black Riders (AMR12A) 'Hush!' said Frodo. 'I think I hear hoofs again.' They stopped suddenly and stood as silent as tree-shadows, listening. There was a sound of hoofs in the lane, some way behind, but coming slow and clear down the wind. Quickly and quietly they slipped off the path, and ran into the deeper shade under the oak-trees. The hoofs drew nearer. They had no time to find any hiding-place better than the general darkness under the trees. - Frodo, Sam and Pippin, when they encounter a Black Rider. Indeed, the Black Riders are in the Shire, and they are looking for the One Ring. There are N hobbits out in their fields, but when they hear the Riders approaching, or feel the fear cast by their presence, they immediately wish to run and hide in M holes located nearby. Now, each hole has space for just 1 hobbit; however, once a hobbit reaches a hole, he is able to make room for one more hobbit by digging away at the earth. The time required to make enough space for a second hobbit is C units. Also, each hole CANNOT hold more than 2 hobbits, even after digging. Also note that a hobbit can begin making space for the next hobbit only after he reaches the hole. You are given the time required to travel from each hobbit's current location to each hole. Find the minimum amount of time it will take before at least K of the hobbits are hiding safely. Input The first line contains T, the number of test cases. The first line of each test case contains 4 integers - N (number of hobbits), M (number of holes), K (minimum number of hobbits to hide) and C (time taken to expand a hole). The next N lines contain M integers each, denoting the time taken for each hobbit to each hole. Output Output one line per test case which contains the minimum time. Constraints 1 ≤ T ≤ 6 1 ≤ N, M ≤ 100 1 ≤ K ≤ min(N, 2 × M) 0 < C < 10,000,000 0 < Time taken by the hobbits to the holes < 10,000,000 Sample Input: 2 3 3 2 10 9 11 13 2 10 14 12 15 12 4 3 3 8 1 10 100 1 10 100 100 100 6 12 10 10 Output: 10 9 Notes/Explanation of Sample For the first test case, there are 3 hobbits and 3 holes, and we need to get at least 2 of them to safety. We can send the first hobbit to the first hole, and the second hobbit to the second hole, thereby taking 10 time units. For the second test case, we can make hobbit #1 reach hole 1 at time 1, hobbit #2 reach hole 1 at time 9 (by when hobbit #1 would have finished digging the hole), and hobbit #3 reach hole 3 at time 6.
33,044
Gandalf vs the Balrog (AMR12B) 'We fought far under the living earth, where time is not counted. Ever he clutched me, and ever I hewed him, till at last he fled into dark tunnels. Ever up now we went, until we came to the Endless Stair. Out he sprang, and even as I came behind, he burst into new flame. Those that looked up from afar thought that the mountain was crowned with storm. Thunder they heard, and lightning, they said, smote upon Celebdil, and leaped back broken into tongues of fire.' - Gandalf, describing his fight against the Balrog. Although Gandalf would not go into the details of his battle, they can be summarized into the following simplified form: both Gandalf and the Balrog have a set of N attacks they can use (spells, swords, brute-force strength etc.). These attacks are numbered from 1 to N in increasing order of Power. When each has chosen an attack, in general, the one with the higher power wins. However, there are a few ("M") anomalous pairs of attacks, in which the lesser-powered attack wins. Initially, Gandalf picks an attack. Then the Balrog counters it with one of the remaining attacks. If the Balrog's counter does not defeat Gandalf's, then we say Gandalf receives a score of 2. If however it does, then Gandalf has exactly one more opportunity to pick an attack that will defeat the Balrog's. If he manages to defeat him now, his score will be 1, whereas if he is still unable to defeat him, his score will be 0. Your task is to determine, given N and the M anomalous pairs of attacks, what will be Gandalf's score, given that both play optimally. Further, in case Gandalf gets a score of 2, you must also determine which attack he could have chosen as his first choice. Note 1: The Balrog can choose only one attack, whereas Gandalf can choose up to two. Note 2: The relation A defeats B is not transitive within the attacks. For example, attack A can defeat attack B, attack B can defeat attack C, and attack C can defeat attack A. Note 3: Between any two attacks A and B, either attack A defeats attack B or attack B defeats attack A. Input The first line will consist of the integer T, the number of test-cases. Each test case begins with a single line containing two integers N and M. This is followed by M lines consisting of 2 integers each x and y, denoting that x and y are an anomalous pair. Output For each test-case, output a single line either 2 A, if Gandalf can defeat any attack the Balrog chooses if he picks attack A, 1, if Gandalf can choose an attack such that even if the Balrog chooses an attack to defeat him, he can choose an attack to defeat the Balrog's chosen card, 0, if none of the above two options are possible for all possible choices of Gandalf's attack(s). Between successive test cases, there should not be any blank lines in the output. Constraints 1 ≤ T ≤ 15 3 ≤ N ≤ 1,000,000 0 ≤ M ≤ min(N(N - 1)/2, 300,000) 1 ≤ x < y ≤ N for all the anomalous pairs (x, y) The sum of M over all test-cases will not exceed 300,000. Example Input: 2 3 0 3 1 1 3  Sample Output: 2 3 1 Explanation of Example In the first case, attack 3 can beat both attacks 1 and 2. So Gandalf just chooses attack 3. In the second case, attack 1 beats 3 which beats 2 which beats 1. No matter which attack Gandalf chooses, the Balrog can pick the one which defeats his, but then he can pick the remaining attack and defeat the Balrog's.
33,045
The Mirror of Galadriel (AMR12D) With water from the stream Galadriel filled the basin to the brim, and breathed on it, and when the water was still again she spoke. 'Here is the Mirror of Galadriel,' she said. 'I have brought you here so that you may look in it, if you will. For this is what your folk would call magic, I believe; though I do not understand clearly what they mean; and they seem also to use the same word of the deceits of the Enemy. But this, if you will, is the magic of Galadriel. Did you not say that you wished to see Elf-magic?' - Galadriel to Frodo and Sam, describing her Mirror. We call a string S magical if every substring of S appears in Galadriel's Mirror (under lateral inversion). In other words, a magical string is a string where every substring has its reverse in the string. Given a string S, determine if it is magical or not. Input The first line contains T, the number of test cases. The next T lines contain a string each.  Output For each test case, output " YES " if the string is magical, and " NO " otherwise. Constraints 1 ≤ T ≤ 100 1 ≤ |S| ≤ 10 S contains only lower-case characters. Example Sample Input: 2 aba ab Sample Output: YES NO Notes / Explanation of Sample Input For the first test case, the list of substrings are : a, b, ab, ba, aba. The reverse of each of these strings is present as a substring of S too. For the second test case, the list of substring are : a, b, ab. The reverse of "ab", which is "ba" is not present as a substring of the string.
33,046
Dyslexic Gollum (AMR12E) 'Light, light of Sun and Moon, he still feared and hated, and he always will, I think; but he was cunning. He found he could hide from daylight and moonshine, and make his way swiftly and softly by dead of night with his pale cold eyes, and catch small frightened or unwary things. He grew stronger and bolder with new food and new air. He found his way into Mirkwood, as one would expect.' - Gandalf, describing Gollum after he ventured forth from Moria. Gollum has spent half a millennium in the long darkness of Moria, where his eyes grew used to the dark, and without caring for reading or writing, he became dyslexic. Indeed, as much as he hates the Moon and the Sun, he also hates strings with long palindromes in them. Gollum has a tolerance level of K, which means that he can read a word so long as it does not contain any palindromic substring of length K or more. Given the values N and K, return how many BINARY strings of length N can Gollum tolerate reading. Input The first line contains T, the number of test cases. Each test case consists of one line containing 2 integers, N and K. Output For each test case, output the answer modulo 1,000,000,007. Constraints 1 <= T <= 100 1 <= N <= 400 1 <= K <= 10 Sample Input: 3 2 2 3 3 3 4 Output: 2 4 8 Notes/Explanation of Sample For the first test case, 01 and 10 are the valid binary strings, while 00 and 11 are invalid. For the second test case, 001, 011, 100, 110 are the valid binary strings. For the third test case, all possible binary strings of length 3 are valid.
33,047
Denethors Decryption of Dequeue permutations (AMR12F) 'Though the Stewards deemed that it was a secret kept only by themselves, long ago I guessed that here in the White Tower, one at least of the Seven Seeing Stones was preserved. In the days of his wisdom Denethor did not presume to use it, nor to challenge Sauron, knowing the limits of his own strength. But his wisdom failed; and I fear that as the peril of his realm grew he looked in the Stone and was deceived: far too often, I guess, since Boromir departed. He was too great to be subdued to the will of the Dark Power, he saw nonetheless only those things which that Power permitted him to see.' - Gandalf. Sauron and Saruman have been communicating from large distances using the Seeing Stones. Denethor, with great difficulty has been able to break into their channel of communication using his strength of will. Despite this however, it seems that their communication has been encrypted. Gondor's spies in Isengard have found out the encryption algorithm they use and have reported back to Denethor. The algorithm is as follows : We refer to a dequeue as a double-ended queue. We define a "dequeue permutation of N" as a permutation of 1 to N that can be got by starting from a dequeue having elements 1, 2, 3, ..., N (in that order with 1 at the front and N at the back) and performing any sequence of N pop_front() or pop_back() operations.  Note that not all permutations of 1 to N are dequeue permutations. For example, with N = 3, you have 3-1-2, 1-3-2 etc. as dequeue permutations whereas 2-1-3, 2-3-1 aren't (you can't have 2 right at the beginning since its not at any end of the dequeue). If Sauron wants to encrypt the number K and send it to Saruman, he would instead send the K'th lexicographically smallest (0-based indexed) dequeue permutation of N. That is, if Sauron wanted to send '0' to Saruman, he would just send 1-2-3-...-N (since this is clearly the smallest lexicographic dequeue permutation of N). Sauron is transmitting the size of his army to Saruman, so that they can coordinate an attack on the Men of Rohan and Gondor. Since Sauron's will is so powerful, Denethor is able to get only vague glimpses of the numbers, and he is able to remember only the first half (floor(N/2) elements) of the permutation. Further, since these images are so vague, his understanding of the numbers happens out of order. For example, Denethor may understand that the 5th number of the permutation is 4, and later on only understand that the 3rd number was 3.  Help him estimate the minimum and maximum possible size of Sauron's army (value of K), given the number N, and incremental understanding of the first half of the permutation, not necessarily in order. NOTE 1: Since the values to be output can be rather large, output the values modulo 1,000,000,007. NOTE 2: It may be the case that Denethor's understanding of the permutation is flawed. If it is not possible to have a dequeue permutation satisfying all the conditions seen so far, output -1. NOTE 3: A permutation p1 is lexicographically smaller than p2 if at the first position where they differ, p1's value is smaller than p2's. Input (STDIN): The first line consists of the integer T, the number of test cases. Each test case begins with a single integer N. This is followed by exactly floor(N/2) lines containing 2 integers each: i and j, denoting that Denethor has understood that the i'th element (1-based) of the supposed permutation is j. Output (STDOUT): For each testcase, output exactly floor(N/2) lines, one for each (i,j) pair. If the recollections till now cannot all be feasible, output '-1' on a line. Else output two space-separated integers: the minimum and the maximum possible value of Sauron's army, K, that are consistent with all the observations seen so far. Between successive test cases, there should not be any blank lines in the output. Constraints: 1 <= T < 3  2 <= N <= 100,000 1 <= i <= floor(N/2) 1 <= j <= N All (i, j) pairs are distinct. And for two pairs (i1, j1) and (i2, j2), you have that i1 != i2 and j1 != j2. Sample Input: 2 3 1 3 32 1 1 3 2 2 32 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 15 15 16 3 Sample Output: 2 3 0 73741816 536870912 805306367 536870912 805306367 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 Notes/Explanation of Sample Input: For the first test case, for N = 3, there are 4 dequeue permutations, lexicographically ordered as 1-2-3, 1-3-2, 3-1-2, and 3-2-1. Denethor sees the first number of the dequeue permutation as 3, and concludes that the permutation can be either 3-1-2, or 3-2-1. In the second test case, we see that (a) the 1st number is 1. (b) the 3rd number is 2 ... this means that the 2nd number has to be 32. (c) the 2nd number is 32 ... this does not add any new information. (d) the 4th number is 4. But this is not possible, since the 4th number can now either be 3 or 31.  Hence it is inconsistent (and none of the further observations can make it consistent). Also notice that in the 2nd test-case, the values have been output modulo 1,000,000,007. 'Though the Stewards deemed that it was a secret kept only by themselves, long ago I guessed that here in the White Tower, one at least of the Seven Seeing Stones was preserved. In the days of his wisdom Denethor did not presume to use it, nor to challenge Sauron, knowing the limits of his own strength. But his wisdom failed; and I fear that as the peril of his realm grew he looked in the Stone and was deceived: far too often, I guess, since Boromir departed. He was too great to be subdued to the will of the Dark Power, he saw nonetheless only those things which that Power permitted him to see.' - Gandalf. Sauron and Saruman have been communicating from large distances using the Seeing Stones. Denethor, with great difficulty has been able to break into their channel of communication using his strength of will. Despite this however, it seems that their communication has been encrypted. Gondor's spies in Isengard have found out the encryption algorithm they use and have reported back to Denethor.   The algorithm is as follows : We refer to a dequeue as a double-ended queue. We define a "dequeue permutation of N" as a permutation of 1 to N that can be got by starting from a dequeue having elements 1, 2, 3, ..., N (in that order with 1 at the front and N at the back) and performing any sequence of N pop_front() or pop_back() operations.  Note that not all permutations of 1 to N are dequeue permutations. For example, with N = 3, you have 3-1-2, 1-3-2 etc. as dequeue permutations whereas 2-1-3, 2-3-1 aren't (you can't have 2 right at the beginning since its not at any end of the dequeue).   If Sauron wants to encrypt the number K and send it to Saruman, he would instead send the K'th lexicographically smallest (0-based indexed) dequeue permutation of N. That is, if Sauron wanted to send '0' to Saruman, he would just send 1-2-3-...-N (since this is clearly the smallest lexicographic dequeue permutation of N). Sauron is transmitting the size of his army to Saruman, so that they can coordinate an attack on the Men of Rohan and Gondor. Since Sauron's will is so powerful, Denethor is able to get only vague glimpses of the numbers, and he is able to remember only the first half (floor(N/2) elements) of the permutation. Further, since these images are so vague, his understanding of the numbers happens out of order. For example, Denethor may understand that the 5th number of the permutation is 4, and later on only understand that the 3rd number was 3.    Help him estimate the minimum and maximum possible size of Sauron's army (value of K), given the number N, and incremental understanding of the first half of the permutation, not necessarily in order.   NOTE 1 : Since the values to be output can be rather large, output the values modulo 1,000,000,007. NOTE 2 : It may be the case that Denethor's understanding of the permutation is flawed. If it is not possible to have a dequeue permutation satisfying all the conditions seen so far, output -1. NOTE 3 : A permutation p1 is lexicographically smaller than p2 if at the first position where they differ, p1's value is smaller than p2's.   Input (STDIN): The first line consists of the integer T, the number of test cases. Each test case begins with a single integer N. This is followed by exactly floor(N/2) lines containing 2 integers each: i and j, denoting that Denethor has understood that the i'th element (1-based) of the supposed permutation is j.   Output (STDOUT): For each testcase, output exactly floor(N/2) lines, one for each (i,j) pair. If the recollections till now cannot all be feasible, output '-1' on a line. Else output two space-separated integers: the minimum and the maximum possible value of Sauron's army, K, that are consistent with all the observations seen so far. Between successive test cases, there should not be any blank lines in the output.   Constraints: 1 <= T < 3  2 <= N <= 100,000 1 <= i <= floor(N/2) 1 <= j <= N All (i, j) pairs are distinct. And for two pairs (i1, j1) and (i2, j2), you have that i1 != i2 and j1 != j2.   Sample Input: 2 3 1 3 32 1 1 3 2 2 32 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 15 15 16 3   Sample Output: 2 3 0 73741816 536870912 805306367 536870912 805306367 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1   Notes/Explanation of Sample Input: For the first test case, for N = 3, there are 4 dequeue permutations, lexicographically ordered as 1-2-3, 1-3-2, 3-1-2, and 3-2-1. Denethor sees the first number of the dequeue permutation as 3, and concludes that the permutation can be either 3-1-2, or 3-2-1. In the second test case, we see that (a) the 1st number is 1. (b) the 3rd number is 2 ... this means that the 2nd number has to be 32. (c) the 2nd number is 32 ... this does not add any new information. (d) the 4th number is 4. But this is not possible, since the 4th number can now either be 3 or 31.  Hence it is inconsistent (and none of the further observations can make it consistent). Also notice that in the 2nd test-case, the values have been output modulo 1,000,000,007.
33,048
The Glittering Caves of Aglarond (AMR12G) 'Strange are the ways of Men, Legolas! Here they have one of the marvels of the Northern World, and what do they say of it? Caves, they say! Caves! Holes to fly to in time of war, to store fodder in! My good Legolas, do you know that the caverns of Helm's Deep are vast and beautiful? There would be an endless pilgrimage of Dwarves, merely to gaze at them, if such things were known to be. Aye indeed, they would pay pure gold for a brief glance! 'And, Legolas, when the torches are kindled and men walk on the sandy floors under the echoing domes, ah! then, Legolas, gems and crystals and veins of precious ore glint in the polished walls; and the light glows through folded marbles, shell-like, translucent as the living hands of Queen Galadriel.' - Gimli, describing to Legolas the Glittering Caves of Aglarond. While these caves are by and large natural, there is one place where the Men of Rohan have chiselled into the rock to create a magnificent exhibit. You have a wall of the cave consisting of 'lighted diamonds' arranged in a N by M grid (basically, you have a light behind each diamond which can be turned on or off). Further, you have a switch corresponding to each row of this diamond-grid. When you operate a switch, it will toggle (flip) the lights corresponding to that row. You are given the current configuration of the lighted diamonds. Gimli challenges Legolas to turn on as many diamonds as possible using EXACTLY K on/off operations of the switches. Since Legolas is an Elf of the Wood and doesn't care much for things that glitter, he instead asks for your help. Note that the same switch (i.e. row) can be chosen multiple times. Input The first line contains the number of test cases T. Each test case contains N, M and K on the first line followed by N lines containing M characters each. The ith line denotes the state of the diamonds in the ith row, where '*' denotes a diamond which is on and '.' denotes a diamond which is off. Output Output T lines containing the answer for the corresponding case. Between successive test cases, there should not be any blank lines in the output. Constraints 1 <= T <= 100 1 <= N, M <= 50 1 <= K <= 100 Sample Input 2 2 2 1 .. ** 2 2 2 .. ** Output 4 2 Notes/Explanation of the Sample: In the first test case, row 1 can be toggled hence leaving all 4 lights to be in the ON state. In the second test case, row 1 (or row 2) can be toggled twice, hence maintaining the state of the initial configuration.
33,049
Saruman of Many Colours (AMR12I) "For I am Saruman the Wise, Saruman Ring-maker, Saruman of Many Colours!" "I looked then and saw that his robes, which had seemed white, were not so, but were woven of all colours. And if he moved they shimmered and changed hue so that the eye was bewildered." - Gandalf the Grey. And so it was that Saruman decided to brand his Uruk-hai army with the many colours that he fancied. His method of branding his army was as follows. He straps his army of N Uruk-hai onto chairs on a conveyor belt. This conveyor belt passes through his colouring-room, and can be moved forward or backward. The Uruk-hai are numbered 0 to N-1 according to the order in which they are seated. Saruman wishes that the i'th Uruk-hai be coloured with the colour c[i]. Further, his colouring-room has space for exactly K chairs. Once the chosen K consecutive Uruk-hai are put into the room, a colour jet sprays all K of them with any fixed colour. The conveyor belt is not circular (which means that the N-1'th and the 0'th Uruk-hai are not consecutive). Note that Uruk-hai can be recoloured in this process. Saruman wants to find out what is the minimum number of times that the jet needs to be used in order to colour his army in the required fashion. If it is not possible to colour the army in the required fashion, output -1. Input The first line contains the number of test-cases T. Each test case consists of 2 lines. The first line contains two space-separated integers, N and K. This is followed by a single like containing a string of length N, describing the colours of the army. The i'th character of the string denotes the colour of the i'th Uruk-hai in the army. Output Output T lines, one for each test case containing the answer for the corresponding test case. Remember if it is not possible to colour the army as required, output -1. Constraints 1 ≤ T ≤ 50 1 ≤ K ≤ N ≤ 20,000 The string c has length exactly N and contains only the characters 'a' ... 'z'. Sample Input: 2 3 2 rgg 3 3 rgg Output: 2 -1 Explanation of Sample In the first test case, soldiers 0 and 1 can first be painted with 'r', and then soldiers 1 and 2 can be painted with 'g'. In the second test case, since N = K, all the soldiers will only have the same color.
33,050
Escape from the Mines (AMR12J) It was after nightfall when they had entered the Mines. They had been going for several hours with only brief halts, when Gandalf came to his first serious check. Before him stood a wide dark arch opening into three passages: all led in the same general direction, eastwards; but the left-hand passage plunged down, while the right-hand climbed up, and the middle way seemed to run on, smooth and level but very narrow. - The Fellowship of the Ring are lost in the Mines. The Mines of Moria are a true testament of Dwarvish genius. And the Fellowship of the Ring are lost in the maze of rooms, halls and caverns. You have managed to acquire a copy of the blueprints, and if only you were part of the Fellowship, Gandalf need not have had to face the Balrog! In this problem, we consider the Mines as consisting of rectangular rooms with their sides aligned parallel to the X (West-East) and Y (South-North) axes. Some rooms are situated within other rooms. The boundaries of any two rooms have no point in common. The rooms are numbered 0 to N-1. Your task is to determine for each room i, which room would you enter if you exit room i. If you exit into the open, output -1. For example, if the blueprints of the Mines looked like: ----- | | | | -----3 ------------------- | ------- | | | | | | | [] | | | | 2 | | | -------1 | | | ------------------0 Then, you should determine that: Room 0 exits into the open (-1) Room 1 exits into Room 0 Room 2 exits into Room 1 Room 3 exits into the open (-1) Input The first line contains an integer N followed by N lines. The i'th line defines the coordinates of the i'th room in the mines: x1 i , y1 i , x2 i , y2 i , where (x1 i , y1 i ) are the coordinates of the southwest corner and (x2 i , y2 i ) are the coordinates of the northeast corner of the i'th room. Output Output N lines, the i'th line containing the number of the room into which the i'th room exits. Output -1 if the i'th room exits into the open. Constraints 1 ≤ N ≤ 100,000 0 ≤ x1 i < x2 i ≤ 1,000,000,000 0 ≤ y1 i < y2 i ≤ 1,000,000,000 The borders of no two rooms have any point in common. Example Input: 4 0 0 10 10 2 3 7 8 3 4 5 6 12 10 13 15 Output: -1 0 1 -1 Notes/Explanation of Sample Input: Given in the diagram above.
33,051
The Loyalty of the Orcs (AMR12K) 'I think that the enemy brought his own enemy with him,' answered Aragorn. 'These are Northern Orcs from far away. Among the slain are none of the great Orcs with the strange badges. There was a quarrel, I guess: it is no uncommon thing with these foul folk. Maybe there was some dispute about the road.' - Aragorn describing the nature of Orcs. Indeed, everyone knows that the Orcs are treacherous creatures who look for their own satisfaction and more often than not disregard the rules. The only way to keep them in line, is by maintaining the chain of command over a strict hierarchy among the ranks, wherein each Orc is responsible to his immediate superior all the way up to the army's head. Further, the powers that be, have decided to have regular checks of their army's loyalties, just in case some Orc has been killed and all his juniors end up turning rogue! There are N orcs, numbered 1 to N, wherein the lead orc is numbered 1. Step 1. Randomly choose a fixed order in which to test Orcs' loyalties. Step 2. Going in this order, you make a "roll-call" to check if the current Orc is alive or not. Step 3. If the current Orc is dead, then he is marked as "deleted". With this information, it is possible to tell which all Orcs will be loyal, and which won't be. However, cunning Master Wormtongue suggests the following optimization: In step 2, if any of the considered Orc's superiors (not necessarily immediate superior) is marked as deleted, then the roll-call is not made. Now, given this algorithm and the hierarchy of the army, along with which Orcs are dead, what is the expected number of roll-calls (taken over all possible orderings in "Step 1") that you save by performing this optimization? Input The first line contains T, the number of test cases. The first line of each test case contains N, the number of orcs in the army. The next N-1 lines contain two space-separated integers u v, denoting that u is the immediate superior of v or vice-versa. The head of the army is the orc labelled 1. The next line contains m, the number of dead orcs. The next line contains m space separated integers, which are the labels of the dead orcs. Output Output one real number for each test case containing the expected number of roll-calls that you save. The results should be accurate within an error range of 10^-6. Constraints 1 <= T <= 5 1 <= N <= 100,000 1 <= u, v <= N u != v The given set of u-v pairs form a valid chain of command. That means every Orc, except the Orc labelled 1, has exactly one immediate superior. Sample Input: 2 2 1 2 1 1 2 1 2 1 2 Input: 0.5 0 Notes / Explanation of Sample For the first test case, the Orc labelled 1 is dead. The two possible orderings are [1, 2] and [2, 1]. With the optimization, for the order [1, 2], we save the roll-call to 2. So, the total number of roll-calls without the optimization is 4, and with the optimization is 3. Expected number of roll-calls is therefore, (4 - 3) / 2 = 0.5 . For the second test case, the Orc labelled 2 is dead. Since he does not have any sub-ordinates, the optimization does not have any effect.
33,052
Entmoot (AMR12C) 'Hoo, ho! Good morning, Merry and Pippin!' he boomed, when he saw them. 'You sleep long. I have been many a hundred strides already today. Now we will have a drink, and go to Entmoot.' 'Where is Entmoot?' Pippin ventured to ask. 'Hoo, eh? Entmoot?' said Treebeard, turning round. 'It is not a place, it is a gathering of Ents - which does not often happen nowadays. But I have managed to make a fair number promise to come.' Indeed, Entmoot cannot be thought of as any particular place, since where it occurs changes from time to time. The choice of the location however, follows a basic principle: Although the Ents (walking and talking Trees - "shepherds of Fangorn Forest") are by and large not hasty, when it comes to gathering for Entmoot, they would like to choose a location that ensures all the Ents can reach as soon as possible. Note however, that the speed they can travel varies from Ent to Ent. Also, although Fangorn Forest has dense overgrowth, with regard to the Ents, the forest poses no obstacles. You are given the locations of N Ents who have agreed to join in for Entmoot, as well as their speeds. You need to find out where Entmoot will occur. Formally, given the (x i , y i ) along with speed s i for each Ent, find the point (X, Y) such that the maximum time taken by any of the Ents to reach (X, Y) is minimized. Output the earliest time when all the Ents can meet. Input The first line contains T, the number of test cases. The first line of each test case contains N, the number of Ents. The next N lines contain three space-separated integers each. The ith of these lines contains : x i , y i , s i . Output Output one line per test case, containing the earliest time when the Ents can meet. Relative and absolute error of 10 -4 are acceptable. Constraints: 1 ≤ T ≤ 10 2 ≤ N ≤ 50 -1,000,000 ≤ x i , y i ≤ 1,000,000 1 ≤ s i ≤ 1,000,000 Sample Input 4 3 0 3 3 4 0 4 -3 -4 5 3 0 10 2 0 20 2 0 40 2 3 0 100 15 0 -100 15 8 0 7 3 0 0 1 10000 0 1 5000 8661 1 Output 1.000000 7.500000 6.666667 5773.751357 Notes/Explanation of Sample In the first test case, all the ents can meet at origin in 1 unit of time. In the second test case, the first and the third ent reach (25, 0) after 7.5 units of time, whereas the second ent reaches there after 2.5 units of time and waits for the remaining ents to arrive. In the third test case, all the ents can meet at origin in 100/15 units of time.
33,053
Wormtongues Mind (AMR12H) Wormtongue looked from face to face. In his eyes was the hunted look of a beast seeking some gap in the ring of his enemies. 'Nay, Eomer, you do not fully understand the mind of Master Wormtongue, ' said Gandalf, turning his piercing glance upon him. 'He is bold and cunning. Even now he plays a game with peril and wins a throw.' - Gandalf, trying to figure out Wormtongue's mind. In fact, Wormtongue's mind is a complicated system of evaluating various variables and parameters. In essence, each parameter is a uniform random floating point variable between 0 and 1 (inclusive). Further, his mind works on calculating best and worst-case values, which are equivalent to min/max of 2 expressions. For example, right now Wormtongue is calculating : 'Chances of escaping' = max('Theoden letting me go', 'Me killing everyone') 'Theoden letting me go' = max('Theoden is forgiving by nature', 'Gandalf advises him to let me go'). 'Me killing everyone' = min('Me killing Gandalf', 'Me killing Theoden'). So, you are given an expression consisting of independent uniform [0, 1] random variables, on which you have an expression consisting of "min", and "max" alone. Help Gandalf figure out Wormtongue's mind by finding the expected value of this expression. Input The first line contains T, the number of test cases. Each test case consists of a single line describing the expression. The characters of the string are derived from the set {'M', 'm', 'x'}, where 'M' stands for max, 'm' stands for min, and 'x' is a random variable Formally, in the expression tree, each node which asks for max is labeled as 'M', each node which asks for min is labelled 'm', and all the leaves are labeled 'x'. The description of the expression is preorder traversal of this tree. For example, Mxmxx describes the expression max(x1, min(x2, x3)). Output For each test case, output one line which contains the expected value of the expression. The results should be accurate within an error range of 10 -6 . Constraints 1 ≤ T ≤ 1, 000 1 ≤ input string length ≤ 100 Example Input: 4 x mxx Mxx MmxxMxx  Output: 0.500000 0.333333 0.666667 0.700000 Explanation of Example For the first test case, it asks for the mean of a random number between 0 and 1, which is 0.5. Notes It is recommended to use long long and long double data types in calculation to avoid precision errors.
33,054
New Year Train (IZHONYT) On the New Year Eve, a government of one country decided to send a train with gifts to each of its towns. For each of the N towns exactly one wagon with gifts was sent. The route was organized in such way that at each place the last wagon would be detached and train would continue on its way, until all gifts were delivered. Just before the departure it turned out that the loading workers did not pay attention to numeration of the wagons and loaded the gifts in random order. It was impossible to detach a wagon from the middle of the train and there was no time to rearrange gifts. Luckily, there was a depot with parallel tracks. At the entrance of the depot each wagon could be directed to any of the tracks and wagons could leave the depot from the other side in the right sequences 1, 2, 3, 4, and so on. Note that we will then be leaving presents in towns in the reversed order (..., 4, 3, 2, 1). For example, let's say we have a train with wagons in the following order: 2, 5, 1, 4, 6, 3. Wagons 2, 5, 6 could be directed to the first track; wagons 1, 4 to the second one and wagon 3 to the third. In this case wagons could leave the depot in the right order. Fortunately, there were enough tracks in the depot to rearrange the train. Input First line of the input contains two integers N and M: the number of wagons in the train and the number of tracks in the depot respectively (1 ≤ N ≤ 800 000, 1 ≤ M ≤ 100 000, M ≤ N). Second line contains N integers: sequence of wagons before the entrance to the depot. It's guaranteed that solution always exists. Output First line of the output must contain N integers: number of track that should be chosen for each wagon from input sequence (tracts are numbered from 1 to M). On the second line print the number of tracks in order the wagons should leave the depot to result in the sequence 1, 2, 3, and so on. If multiple solutions exists, print the one that results in lexicographically smallest sequence in the first line of the output. Example Input 6 3 2 5 1 4 6 3 Output 1 1 2 2 1 3 2 1 3 2 1 1
33,055
Slikar (CSLIKAR) The evil emperor Cactus has in his possession the Magic Keg and has flooded the Enchanted Forest! The Painter and the three little hedgehogs now have to return to the Beaver's den where they will be safe from the water as quickly as possible! The map of the Enchanted Forest consists of R rows and C columns. Empty fields are represented by '.' characters, flooded fields by '*' and rocks by 'X'. Additionally, the Beaver's den is represented by 'D' and the Painter and the three little hedgehogs are shown as 'S'. Every minute the Painter and the three little hedgehogs can move to 4 neighbouring fields (up, down, left or right). Every minute the flood expands as well so that all empty fields that have at least one common side with a flooded field become flooded as well. Neither water nor the Painter and the three little hedgehogs can pass through rocks. Naturally, the Painter and the three little hedgehogs cannot pass through flooded fields, and water cannot flood the Beaver's den. Write a program that will, given a map of the Enchanted Forest, output the shortest time needed for the Painter and the three little hedgehogs to safely reach the Beaver's den. Note: The Painter and the three little hedgehogs cannot move into a field that is about to be flooded (in the same minute). Input The first line of input will contain two integers, R and C, smaller than or equal to 50. The following R lines will each contain C characters ('.', '*', 'X', 'D' or 'S'). The map will contain exactly one 'D' character and exactly one 'S' character Output Output the shortest possible time needed for the Painter and the three little hedgehogs to safely reach the Beaver's den. If this is impossible output the word “KAKTUS” on a line by itself. Example Input: 3 6 D...*. .X.X.. ....S. Output: 6
33,056
The Mad Numerologist (MADN) Numerology is a science that is used by many people to find out a mans personality, sole purpose of life, desires to experience etc. Some calculations of numerology are very complex, while others are quite simple. You can sit alone at home and do these easy calculations without taking any ones help. However in this problem you wont be asked to find the value of your name. To find the value of a name modern numerologists have assigned values to all the letters of English Alphabet. The table above shows the numerical values of all letters of English alphabets. Five letters A, E, I, O, U are vowels. Rests of the letters are consonant. In this table all letters in column 1 have value 1, all letters in column 2 have value 2 and so on. So T has value 2, F has value 6, R has value 9, O has value 6 etc. When calculating the value of a particular name the consonants and vowels are calculated separately. The following picture explains this method using the name "CHRISTOPHER RORY PAGE". So you can see that to find the consonant value, the values of individual consonants are added and to find the vowel value the values of individual vowels are added. A mad Numerologist suggests people many strange lucky names. He follows the rules stated below while giving lucky names. The name has a predefined length N . The vowel value and consonant value of the name must be kept minimum. To make the pronunciation of the name possible vowels and consonants are placed in alternate positions. Actually vowels are put in odd positions and consonants are put in even positions. The leftmost letter of a name has position 1; the position right to it is position 2 and so on. No consonants can be used in a name more than five times and no vowels can be used in a name more than twenty-one times Following the rules and limitations above the name must be kept lexicographically smallest. Please note that the numerologists first priority is to keep the vowel and consonant value minimum and then to make the name lexicographically smallest. Input First line of the input file contains an integer N (0 < N <= 250) that indicates how many sets of inputs are there. Each of the next N lines contains a single set of input. The description of each set is given below: Each line contains an integer n (0 < n < 211) that indicates the predefined length of the name. Output For each set of input produce one line of output. This line contains the serial of output followed by the name that the numerologist would suggest following the rules above. All letters in the output should be uppercase English letters. Example Input: 3 1 5 5 Output: Case 1: A Case 2: AJAJA Case 3: AJAJA
33,057
New Strategy (PCPC12D) Meeda will compete this year in the ACM-ICPC world finals, but he is a crazy guy, he created a new strategy to attack the problem set. His new strategy is to solve the problems according to their names. He’ll sort the problem set according to the following rules. Remove all whitespace characters from the problem names. Replace any capital letters with the corresponding small one. i.e ‘A’ will be ‘a’. count the occurrence of each character. Problem A comes before problem B, if A contains lexicographically smaller characters more than B i.e A = “cba” comes before B = “bc” because A contains 1 'a' and B contains 0 'a'. But as you may know that meeda is a very lazy guy and he needs to train for this strategy before the world finals, so he needs your help to write an efficient program to help him in the training. Input The first line of the input contains T, number of test cases, each test case starts with an integer n (0 < n < 1000) number of problems, follow n lines each containing string s. The ith line is the name of the ith problem. s will be a sequence of characters (a-z, A-Z or any white space character), length of s is less than 200 characters. Output First line of each test case should contains “case: ” without double quotes followed by the test case number starting from 1, then follow problem names sorted as described above. Input 2 2 abc ab 4 bcsaasd dbasaaaa azzz bayy Output case: 1 abc ab case: 2 dbasaaaa bcsaasd bayy azzz note : sorry for the wrong description. Max length is 200.
33,058
Snakes and Ladders (PCPC12E) Snakes and Ladders (or Chutes and Ladders) is an ancient Indian board game regarded today as a worldwide classic. It is played between two or more players on a game board having numbered squares (fields) on a grid. A number of "ladders" and "snakes" (or "chutes") are pictured on the board, each connecting two specific board squares. The object of the game is to navigate one's game piece from the start (Bottom square) to the finish (Top Square), helped or hindered by ladders and snakes, respectively. The historic version had root in morality lessons, where a player's progression up the board represented a life journey complicated by virtues (ladders) and vices (snakes).  If, after throwing a dice, a player's token lands on the lower-numbered end of a "ladder", the player moves his token up to the ladder's higher-numbered square. If he lands on the higher-numbered square of a "snake" (or chute), he must move his token down to the snake's lower-numbered square. If any of those cases takes places, we will call a square unstable. Otherwise it is stable. The game is a simple race contest lacking a skill component, and is popular with young children. In this problem you’re required to calculate the minimum number of 6-sided die throws to move your game piece from the start (bottom square) to the finish (top square). Formal game description Fields are arranged on an NxM grid and numbered from 1 to N*M. Last field, indicated by N*M, is referred to as Top Square. Each player starts with a token on a square at position "0" (the imaginary space beside the “1” grid field; Bottom Square), which is always stable. So in total we have N*M+1 fields. In every turn player throws the die and moves up by the given number of squares. If that would result in a field higher than Top Square, then token is not moved. If the square that token ends on is unstable, it is moved as indicated by ladder or snake. This is repeated until token is placed a stable field. You can assume that a stable field can be reached from any field on the board. If this final, stable field is the Top Square, game ends and player wins. Input Input contains multiple test cases First line of each test case contains integers N, M, S, L. where n and m are the board dimensions, N (0 < N <= 100), M (0 < M <= 100), and S and L are number of snakes and ladders respectively. Next S lines describes snakes. Each line contains two integers: h and t, where h is the snake’s head position and t is the snake tail position. (0 < t < h <=N*M), Next L lines describes ladders. Each line contains two integers: p and q where p is the ladder’s bottom and q is the ladder’s top (0 < p < q < N*M). The input will be terminated by the end of file. NOTE! There could be more snakes and/or ladders leading from a single field. In such a case use the last snake/ladder specified in the input. Output Print one line per test case containing the minimum number of dice throws. If you cannot reach to the finish square print -1 Sample Input 1 1 0 0 1 2 1 0 2 1 5 10 3 5 16 6 47 26 49 11 1 38 4 14 9 31 40 42 36 44 Output 1 -1 3 See also: Snakes and Ladders Again
33,059
Snakes and Ladders Again (PCPC12F) Snakes and Ladders (or Chutes and Ladders) is an ancient Indian board game regarded today as a worldwide classic. It is played between two or more players on a game board having numbered squares (fields) on a grid. A number of "ladders" and "snakes" (or "chutes") are pictured on the board, each connecting two specific board squares. The object of the game is to navigate one's game piece from the start (Bottom square) to the finish (Top Square), helped or hindered by ladders and snakes, respectively. The historic version had root in morality lessons, where a player's progression up the board represented a life journey complicated by virtues (ladders) and vices (snakes).  If, after throwing a dice, a player's token lands on the lower-numbered end of a "ladder", the player moves his token up to the ladder's higher-numbered square. If he lands on the higher-numbered square of a "snake" (or chute), he must move his token down to the snake's lower-numbered square. If any of those cases takes places, we will call a square unstable. Otherwise it is stable. The game is a simple race contest lacking a skill component, and is popular with young children. In this problem you’re required to calculate the expected number of 6-sided die throws to move your game piece from the start (bottom square) to the finish (top square). Formal game description Fields are arranged on an NxM grid and numbered from 1 to N*M. Last field, indicated by N*M, is referred to as Top Square. Each player starts with a token on a square at position "0" (the imaginary space beside the “1” grid field; Bottom Square), which is always stable. So in total we have N*M+1 fields. In every turn player throws the die and moves up by the given number of squares. If that would result in a field higher than Top Square, then token is not moved. If the square that token ends on is unstable, it is moved as indicated by ladder or snake. This is repeated until token is placed a stable field. You can assume that a stable field can be reached from any field on the board. If this final, stable field is the Top Square, game ends and player wins. Input Input contains multiple test cases First line of each test case contains integers N, M, S, L. where n and m are the board dimensions, N (0 < N <= 10), M (0 < M <= 10), and S and L are number of snakes and ladders respectively. Next S lines describes snakes. Each line contains two integers: h and t, where h is the snake’s head position and t is the snake tail position. (0 < t < h <=N*M), Next L lines describes ladders. Each line contains two integers: p and q where p is the ladder’s bottom and q is the ladder’s top (0 < p < q < N*M). The input will be terminated by the end of file. NOTE! There could be more snakes and/or ladders leading from a single field. In such a case use the last snake/ladder specified in the input. Output Print one number per test case (each in separate line), expected number of dice throws needed to reach the Top Square. It's guaranteed that the Top is always reachable. Your round the result to exactly 3 decimal places. Sample Input 5 10 3 5 16 6 47 26 49 11 1 38 4 14 9 31 40 42 36 44 Output 30.198 Before you solve this you may want to try: Snakes and Ladders
33,060
Mosque (PCPC12G) Islam prayer in congregation (jama'ah) is considered to have more social and spiritual benefit than praying by oneself. When praying in congregation, the people stand in straight parallel rows behind the chosen imam, facing Qibla (The Qibla is the direction that should be faced when a Muslim prays). Sometimes some of these rows are cut by poles (n poles divide the row into n+1 parts), and some of the rows do not contain poles (the whole row is just one part). Muslims prefer to stand in the rows which are free of poles, so they may leave one row empty and use the next one if it has fewer poles, but they can’t leave two consecutive rows empty. A mosque is divided into n rows each row may contains one or more poles. Each row free of poles can have m Muslims and every additional pole decreases this number by 2, so if the row contains 2 poles, number of Muslims who can stand in this row is m - 4. In this problem you are required to arrange the Muslims in rows where number of poles cutting these rows is minimized. Input Input contains multiple test cases. Each test case will start with the number of n (0 < n ≤ 100), m (10 ≤ m ≤ 200), and t (0 < t ≤ 20,000), where n is number of rows, m is number of Muslims per row, and t is the total number of people in the mosque, followed by n lines each containing the number of poles in each row. It is guaranteed that the mosque always can fit all the Muslims. Input will be terminated by end of file. Output For each test case, print one line containing the minimum number of poles cutting the prayer rows. Sample Input: 8 10 26 1 2 0 2 1 1 1 2 8 10 27 1 2 0 2 1 1 1 2 8 10 27 1 2 1 2 2 1 1 1 Output: 2 3 5
33,061
Beggars (PCPC12H) Begging nowadays is an organized profession and team work is extremely important. Beggars target special occasions to maximize revenue, such as Muslim Friday prayers. They wait outside the mosque until the prayer ends and ask people for money as people leave the mosque. In this problem you are to help two beggars to maximize their revenue on Friday after the Friday prayers. These beggars are experienced and know everything they need, specifically they know exactly when each mosque ends the prayer and how much money they will gain if at least one of them stands in front of that mosque when the prayer ends (there is no use if both of them stand at the same mosque). In their town there are n mosques on a straight line and you will be given the x coordinate for each mosque. The time needed for a beggar to travel from one mosque a to another mosque b is |xa-xb| units of time. As you know, these baggers are professionals and take no time to collect the money from a mosque if they happen to be there when the prayer ends, and can immediately start moving to another mosque. Of course the beggars can choose to initially start from any mosque. Your task here is to compute the maximum amount of money they can collect together. Input Specification Input contains multiple test cases. Each test case starts with number of mosques 1<=n<=100, followed by n lines. Each line consists of three 32-bits signed integers x, t, and m representing the x-coordinate of the mosque, the time when the prayer ends, and the amount of money that can be collected from this mosque. The input will be terminated when n equals 0 and should not be treated as a test case. Output Specification For each test case you should print a single integer, the maximum amount of money that can be collected by the two beggars. Sample Input 3 7 6 19 2 3 18 9 8 13 4 1 4 5 3 4 5 2 5 5 4 5 5 4 1 4 5 3 4 5 2 5 5 5 5 5 0 Sample Output 50 20 15
33,062
peaks (PCPC12I) You are given a sequence of numbers s, you are required to find 3 indices i, j, k, where i < j < k and (s[i] <= s[j] >= s[k] or s[i] >= s[j] <= s[k]) if there are many solutions you should find the one where |s[i]-s[j]| + |s[j]-s[k]| is maximized, if there are still many solutions you should find the one which comes earlier in order (i.e. i1, j1, k1, comes before i2, j2, k2, if i1 < i2, or if i1 = i2, and j1 < j2, or if i1 = i2, j1 = j2, and k1 < k2). Input The problem will be tested on multiple test cases, the first line of the input contains an integer n representing the size of the sequence (3 <= n <= 10^6) (^ means power), then followed by n integers. All numbers in this sequence do not exceed 10^6 in absolute value. The input is terminated by end of file. Output For each test case, output a line containing the 3 indices of the pattern i, j, k space separated. If there is no such pattern output -1 instead. Sample Input: 7 2 3 1 7 2 4 8 5 2 3 5 7 1 Output: 3 4 5 1 4 5
33,063
Amr Samir (PCPC12J) Amr started to learn division. So he gave a list of numbers to his friend and asked him to find all the divisors of each number in the given list. Now Amr has a new list of numbers containing all divisors of his original list. As Amr loves playing with numbers, he now thinks about the repeated numbers in the new list of divisors. However this time Amr is interested in the luckiest divisor! Lucky divisor is defined by Amr as follows: a divisor D is lucky if D divides f, where f is the frequency of this number D in the new list. Obviously f must be greater than zero. The luckiest divisor is the divisor D that divides f where f is the maximum and D is the smallest one. Since Amr is too lazy to write a program that solves this problem, he decided to submit it to the PCPC chief judge to put it as a problem for the teams to write a solution to it. Can you write this program for Amr? Input The first line contains a positive integer t <= 100, then follow t test cases. Each test case start with a line containing a single positive integer n <= 10000 number of divisors in Amr’s new list, then follows n positive integers a1, ai, ... an (ai <= 100). Output Your code should print an integer for each test case representing the luckiest divisor or -1 if there is no lucky divisor. Sample Input 2 5 2 2 3 3 3 7 2 2 2 2 3 3 3 Output 3 2
33,064
DNA (MUTDNA) Biologists have discovered a strange DNA molecule, best described as a sequence of N characters from the set {A, B}. An unlikely sequence of mutations has resulted in a DNA strand consisting only of A's. Biologists found that very odd, so they began studying the mutations in greater detail. They discovered two types of mutations. One type results in changing a single character of the sequence (A → B or B → A). The second type changes a whole prefix of the sequence, specifically replacing all characters in positions from 1 to K (for some K between 1 and N, inclusive) with the other character (A with B, B with A). Compute the least possible number of mutations that could convert the starting molecule to its end state (containing only A characters). Mutations can occur in any order Input The first line of input contains the positive integer N (1 ≤ N ≤ 1 000 000), the length of the molecule. The second line of input contains a string with N characters, with each character being either A or B. This string represents the starting state of the molecule. Output The first and only line of output must contain the required minimum number of mutations. Example Input 1: 4 ABBA Output 1: 2 Input 2: 5 BBABB Output 2: 2 Input 3: 12 AAABBBAAABBB Output 3: 4
33,065
KOSARE (KOSARE) Mirko found N boxes with various forgotten toys at his attic. There are M different toys, numbered 1 through M, but each of those can appear multiple times across various boxes. Mirko decided that he will choose some boxes in a way that there is at least one toy of each kind present, and throw the rest of the boxes away. Determine the number of ways in which Mirko can do this. Input The first line of input contains two integers N and M (1 ≤ N ≤ 1 000 000, 1 ≤ M ≤ 20). Each of the following N lines contains an integer K i (0 ≤ K i ≤ M) followed by Ki distinct integers from interval [1, M], representing the toys in that box. Output The first and only line of output should contain the requested number of ways modulo 1 000 000 007. Example Input 1: 3 3 3 1 2 3 3 1 2 3 3 1 2 3 Output 1: 7 Input 2: 3 3 1 1 1 2 1 3 Output 2: 1 Input 3: 4 5 2 2 3 2 1 2 4 1 2 3 5 4 1 2 4 5 Output 3: 6
33,066
SQL Queries (PUCMM331) Structured Query Language (SQL) is a special-purpose programming language designed for manipulating relational data. Its most known feature is perhaps the Query, that is, a mechanism by which data can be retrieved based on custom criteria. The general syntax to construct a SQL Query with filtering criteria is as follows: SELECT [list of fields] FROM [table] WHERE [criteria] Let us review an example. Consider we have the following table of competitive programmers: Nickname Country CF_Rating TC_Rating tourist BY 3205 3693 Petr RU 2676 3738 Egor RU 2732 3463 cjtoribio DO 2019 1381 niquefa_diego CO 2059 1896 Un_Exisstin3 PE 2400 1499 If we wanted to retrieve all competitive programmers who have a CodeForces rating less than 2200 or a TopCoder rating of at most 1500, we could construct the following query: SELECT Nickname FROM Comp_Programmers WHERE CF_Rating < 2200 OR TC_Rating <= 1500 In this example, the query would return nicknames cjtoribio , niquefa_diego and Un_Exisstin3 . We will consider a simplified SQL statement. Assume there is only one table with the same structure as the one provided in the above example. Your program will receive a single criteria with exactly two conditions on the columns CF_Rating and TC_Rating, assembled with either the AND or the OR operator. With this criteria, your program must output the corresponding nicknames of the retrieved rows. Input The first line of input contains M (1 <= M <= 50), the number of rows on the table and N (1 <= N <= 20), the number of queries to be performed. The next M lines contain the rows of the table. Each row is completely described in a single line and contains four tokens separated by single space: Nickname, which is a string of length not exceeding 20; Country, an uppercase string of length 2 consisting of letters [A-Z]; CF_Rating, a positive integer in the range [0, 5000] and TC_Rating, similar to CF_Rating. Nicknames are not unique. The following N lines contain the list of queries to be performed. Each query is described in a single line. The format of a query is as follows (without brackets): [CF_Rating | TC_Rating] [ < | > | <= | >= ] [positive_integer] [AND | OR] [CF_Rating | TC_Rating] [ < | > | <= | >= ] [positive_integer]. Output For each query i enumerated from 1 to N: - output as its first line "Query #i:" - output each nickname on a separate line The list of nicknames must be printed in lexicographical order. Examples Input 6 2 tourist BY 3205 3693 Petr RU 2676 3738 Egor RU 2732 3463 cjtoribio DO 2019 1381 niquefa_diego CO 2059 1896 Un_Exisstin3 PE 2400 1499 CF_Rating < 2200 OR TC_Rating <= 1500 CF_Rating > 1 AND TC_Rating >= 3600 Output Query #1: Un_Exisstin3 cjtoribio niquefa_diego Query #2: Petr tourist
33,067
Dividing Xorland (PUCMM333) Xorland is a beautiful Kingdom located in the northern part of the Hispaniola Island. You can picture it as a perfect n×n square. Incredibly, n 2 people live there, each in a perfect 1×1 square. They all have an integer spirit in the range [1, 10 6 ]. The King died recently and, as is custom, Xorland must be divided into three parts. Xorlandic people love to apply the Xor operation on their spirits, so it is normal to expect them to use it also to divide the land. Xorland must be divided by two parallel lines. These parallel lines must also be parallel to one side of the square. Each part will be non-empty. To divide the land, this is what they do: Place two parallel lines inside the square. Construct a non-empty subset of the spirits of the first part and call it A. Construct a non-empty subset of the spirits of the second part and call it B. Construct a non-empty subset of the spirits of the third part and call it C. Apply the Xor operation on A, on B and on C. Find the value of Xor(A) + Xor(B) + Xor(C) and call it SUM. Eat and Drink joyfully for SUM days straight. Between us, Xorlandic people LOVE eating and drinking! That is why they want to find the partition that yields the greatest sum. Help them! Write a program that finds this number. Input The first line of input contains N (3 ≤ N ≤ 5), the length of the sides of the squared area. Then follow N lines, each bearing a spirit. Each spirit will be a positive integer in the range [1, 10 6 ]. Output Output the greatest sum possible. Sample Cases Input 3 1 1 1 2 2 2 3 3 3 Output 9 In this case, the optimal choice is to divide vertically. Column 1 is {1, 2, 3}; Column 2 is {1, 2, 3} and Column 3 is {1, 2, 3}. Taking A = {3}, B = {3} and C = {3} we get 3 × Xor{3} = 9, the optimal answer. Note that other subsets may yield 9 as well.
33,068
White Hats (PUCMM334) There are a number of people in a room (between 2 and 100), and each of them wears a hat which is either black or white. Every person counts the number of other people wearing white hats. You are given the number counted by each person. Print the total number of people wearing white hats, or -1 if count doesn't correspond to a valid situation. Input The first line is N, the number of persons. Then N space separated integers follow, each one denoting the number of white hats each person sees. Output Print the total number of people wearing white hats, or -1 if count doesn't correspond to a valid situation. Example Input: Output: 3 2 2 1 1 Input: Output: 3 3 2 2 2 Input: Output: 2 0 0 0 Input: Output: 2 -1 10 10
33,069
The Rook and The Rookette (PUCMM335) Once upon a time, there was a noble rook called Danny who lived in a normal 8x8 chessboard. All squares lived in peace and Danny was a joyful rook, moving either vertically or horizontally across the board, never going off limits. Oh boy did he enjoy moving! He spent all days visiting the 64 squares and bringing flowers and other gifts to them. All squares loved Danny very much, even though they felt sorry for him because there was no Rookette for him to date. The King took notice of the squares’ gossiping and he did something very remarkable. He arranged Danny a date with María, a Rookette from another chessboard. So, María stepped in one of the squares and Danny went immediately after her. However, the King made sure it wasn’t easy for Danny. He told him: “Danny, I love you very much. We all do. What I am doing right now is because I love you.” Danny was perplexed, without a clue. “What do you mean, Oh righteous King?” Suddenly, the King arranged M bombs in M squares. “In life, you must work hard to achieve your dreams. I cannot just hand María over to you. You need to earn your right to date her.” “Oookkkk…” said Danny, in a doubtful tone. “I may also step in one of the squares. Go after her!” And off went Danny. Assume Danny is very desperate to meet her, so he will try to get to her in the shortest possible way. The King  wants to prolong Danny’s path (maybe to have him think thoroughly about becoming a man). The King needs to decide where he will step in, he has N empty squares to choose from. Write a program that outputs the length of the path should both Danny and the King act optimally. There will always be a path. Input There is a single test case per input file. The first 8 lines contain 8 characters each, and they represent the initial state of the chessboard. The lines are enumerated from 0 to 7 and so are the 8 characters of each line. The character at position (i, j)  can be one of the following: ‘.’ : an empty square. ‘#’ : a bomb. ‘?’ : the princess. '$' : Danny. The following line contains N (0 <= N <= 10), representing the number of empty squares the King has to choose from. Then follow N lines. Each of these lines contain two integers Xi, Yi (0 <= Xi, Yi <= 7), the position of an empty square. Output Write a single line containing the length of the path Danny takes to reach María, if both Danny and the King act optimally. Sample Input $......? ######## ######## ######## ######## ######## ######## #######. 1 7 7 Output 7
33,070
FizzBuzz Happy 2013 (ADITYA13) Having cleared the ACM ICPC online round you receive a job offer of teaching JAVA programming to High School Students of Byteland. You gladly take the job offer and after a few days of teaching you give the students a program to write. You ask them to write a FIZZBUZZ program. They are either too smart or too lazy. They argue that it is too difficult and challenge you to do better than that without using any English letters. You consult senior programmer Mitch who suggests you a way out of the problem. "Do it in BF," he says. Tjandra suggests you do it in Whitespace. Input Two space separated one digit integers A and B. Then a newline. Then a string C of maximum length 5 followed by a newline. Then another string D of max length 5 followed by a newline. It is guaranteed that gcd(A,B) < A and gcd(A,B) < B. Also the strings comprise only alphanumeric characters. Output For all numbers in the set [1, 99] print C if the number is divisible by A, print D if divisible by B, print C concat D if divisible by both and the number (with preceding zeroes if required) if it divisible by neither A nor B. Example Input: 2 3 Happy 2013 Output: 01 Happy 2013 Happy 05 Happy2013 07 ..........and you get the idea Wishing all of you a HAPPY NEW YEAR 2013 :) Edit: 05-01-2013 I am giving you all a link to mostafa_36a2's solution. You would be pleased... Download the encrypted text solution
33,071
Magic Sticks (STICKS) We have N sticks are lined up in a queue with different distances between them, and each stick is leaning on the left stick (look at figure). L: the length of the stick. D: the distance between the stick head point and the left one head point. We catch the first stick (that length L0) and keep it vertical. Determine the total time that expected to fall down all sticks if the first stick moved away (assume that each stick's bottom end will not be displaced, and when the stick reach ground it will vanish and the right one start to fall). You will have V (linear velocity for the head point) at time = 1 second (from the stick start to fall, if we assume that stick will not stop and keeping same motion type). Suppose that weight force has stable effect on the stick in direction and value. Input the first line: N, L0 next N-1 Line: Lk, Dk, Vk(1) Output One number T (total time in millisecond). Example Input: 2 8.75 10 8.7 25000 Output: 2 Constraints 2 <= N <= 5000 1 <= L <= 1000000 1 <= V <= 1000000.
33,072
Tom and Jerry (MAY99_1) Tom and Jerry is a favourite cartoon of many of us. One day Manku was sitting watching an episode of Tom and Jerry where he found that Tom and Jerry both entered a rectangular maze and Tom was after Jerry, but Jerry being the hero, returned safely. Manku then start making different scenarios and wondering that if Jerry moves optimally and Tom knows entire path that Jerry is expected to take, then will Jerry be able to escape out of the maze or not? Moreover Manku added 1 rule to this that if Jerry moves from position A to position B, then at any cost he is not allowed to return from position B to position A. Jerry, if is at the escape positions of the maze, in the beginning, then he can't exit from that same position. Moreover he can't escape if he is caught by Tom at any position. Jerry and Tom can move up, down, left, right or wait at their current position. If it is guaranteed that either Jerry would escape or Tom would catch him. All characters at row = 0 or row = m-1 or column = 0 or column = n-1, which are '.' or 'J' or 'T' are escape positions. Input Each input file consist of only 1 test case. First line of input contains 2 numbers m and n, both integers are less than or equal to 100, the size of the rectangular maze. Then m lines follows containing n characters each: . means an open space so that Tom or Jerry can move there. # means a closed place. T means starting position of Tom. J means starting position of Jerry. Output Output single line containing a character W and integer D, where W is 'J' if Jerry can escape or else 'T' and D is the minimum time taken by Jerry to escape (if W is 'J') or maximum time for which Jerry is alive (if W is 'T') Example Input 1: 4 4 #..J #... #.T. #### Output 1: J 1 Input 2: 6 3 ### #J# #.T ### ### #.# Output 2: T 2 Input 3: 7 7 ......# ....... ....... ...J... ...T... ....... #...... Output 3: J 3 Input 4: 7 7 #.....# #...... #...... J...... #..T... #...... #...... Output 4: J 4 Explanation In the first test case Jerry will move 1 step to his left and would escape. In the second test case Jerry can't escape so he will remain at his position and will be caught after 2 moves. In the third test case Jerry will move 3 steps to his left and will escape. In the fourth test case Jerry will move 1 step to his right and then 3 steps up to escape.
33,073
Totient in permutation (easy) (TIP1) In number theory, Euler's totient (or PHI function), is an arithmetic function that counts the number of positive integers less than or equal to a positive integer N that are relatively prime to this number N. That is, if N is a positive integer, then PHI(N) is the number of integers K for which GCD(N, K) = 1 and 1 ≤ K ≤ N. We denote GCD the Greatest Common Divisor. For example, we have PHI(9)=6. Interestingly, PHI(87109)=79180, and it can be seen that 87109 is a permutation of 79180. Input The input begins with the number T of test cases in a single line. In each of the next T lines there are an integer M. Output For each given M, you have to print on a single line the value of N, for which 1 < N < M, PHI(N) is a permutation of N and the ratio N/PHI(N) produces a minimum. If there's several answers output the greatest, or if need, "No solution." without quotes. Leading zeros are not allowed for integers greater than 0. Example Input: 3 22 222 2222 Output: 21 63 291 Explanations : For the first case, in the range ]1..22[, the lonely number n for which phi(n) is in permutations(n) is 21, (we have phi(21)=12). So the answer is obviously 21. For the second case, in the range ]1..222[, there's two numbers n for which phi(n) is in permutations(n), we have phi(21)=12 and phi(63)=36. But as 63/36 is equal to 21/12, we're taking the greater : 63. For the third case, in the range ]1..2222[, there's four numbers n for witch phi(n) is in permutations(n), phi(21)=12, phi(63)=36, phi(291)=192 and phi(502)=250. Within those solutions 291/192 is the minimum, we output 291. Constraints 1 < T < 10^5 1 < M < 10^7 Code size limit is 10kB ; less than 500B of python3 code can get AC under 2s. After that you may try TIP2 . @Speed addicts : my C code ran in 0.02s, and my fastest python3.2 code ran in 1.21s, (0.90s in py2.7) Edit 2017-02-11, after compiler updates. My old C code ends in 0.00s, my old Python code ends in 0.05s !!!
33,074
Totient in permutation (medium) (TIP2) In number theory, Euler's totient (or PHI function), is an arithmetic function that counts the number of positive integers less than or equal to a positive integer N that are relatively prime to this number N. That is, if N is a positive integer, then PHI(N) is the number of integers K for which GCD(N, K) = 1 and 1 ≤ K ≤ N. We denote GCD the Greatest Common Divisor. For example, we have PHI(9)=6. Interestingly, PHI(87109)=79180, and it can be seen that 87109 is a permutation of 79180. Input The input begins with the number T of test cases in a single line. In each of the next T lines there are an integer M. Output For each given M, you have to print on a single line the value of N, for which 1 < N < M, PHI(N) is a permutation of N and the ratio N/PHI(N) produces a minimum. If there's several answers output the greatest, or if need, "No solution." without quotes. Leading zeros are not allowed for integers greater than 0. Example Input: 3 22 222 2222 Output: 21 63 291 Explanations : For the first case, in the range ]1..22[, the lonely number n for witch phi(n) is in permutations(n) is 21, (we have phi(21)=12). So the answer is obviously 21. For the second case, in the range ]1..222[, there's two numbers n for witch phi(n) is in permutations(n), we have phi(21)=12 and phi(63)=36. But as 63/36 is equal to 21/12, we're taking the greater : 63. For the third case, in the range ]1..2222[, there's four numbers n for witch phi(n) is in permutations(n), phi(21)=12, phi(63)=36, phi(291)=192 and phi(502)=250. Within those solutions 291/192 is the minimum, we output 291. Constraints 1 < T < 10^2 1 < M < 10^12 Code size limit is 10kB ; the upper bound was set at 10^12 to make a (C/pascal/...)-solution easier to write. Constraints allow Python3 users to get AC under 1.86s (with a sub-optimal solution). (Edit 2017-02-11, after compiler updates) If if you get TLE, you should try first TIP1 . If it's too easy for you TIP3 is made for you ;-)
33,075
Totient in permutation (hard) (TIP3) In number theory, Euler's totient (or PHI function), is an arithmetic function that counts the number of positive integers less than or equal to a positive integer N that are relatively prime to this number N. That is, if N is a positive integer, then PHI(N) is the number of integers K for which GCD(N, K) = 1 and 1 ≤ K ≤ N. We denote GCD the Greatest Common Divisor. For example, we have PHI(9)=6. Interestingly, PHI(87109)=79180, and it can be seen that 87109 is a permutation of 79180. Input There is only one number M. Output For the given M, you have to print on a single line the value of N, for which 1 < N < M, PHI(N) is a permutation of N and the ratio N/PHI(N) produces a minimum. If there's several answers output the greatest, or if need, "No solution." without quotes. Leading zeros are not allowed for integers greater than 0. Example Input: 22 Output: 21 Input: 222 Output: 63 Input: 2222 Output: 291 Explanations For the first case, in the range ]1..22[, the lonely number n for which phi(n) is in permutations(n) is 21, (we have phi(21)=12). So the answer is obviously 21. For the second case, in the range ]1..222[, there's two numbers n for which phi(n) is in permutations(n), we have phi(21)=12 and phi(63)=36. But as 63/36 is equal to 21/12, we're taking the greater : 63. For the third case, in the range ]1..2222[, there's four numbers n for which phi(n) is in permutations(n), phi(21)=12, phi(63)=36, phi(291)=192 and phi(502)=250. Within those solutions 291/192 is the minimum, we output 291. Constraints 1 < M < 10^27 If you got TLE, you should consider before TIP2 . Enjoy. Warning : don't try to investigate the input number, judge is strict and interactive ; test case is randomly changing, staying equivalent in difficulty. Please don't use spurious spaces and end your answer with '\n' ; e.g. "21\n" awaited for the sample. There is many ways to optimize the solution for this problem, to get AC here, you'll need to find many of them. Time limit allows python3 solutions. There is different judges, time is the sum of them. (Edit 2017-02-11, after compiler changes : my Py3 solution ends in 25s, approx 2.5s per file, 10 files.)
33,076
The BrainFast Processing! Classical version (FAST_BF) Warning : Only Brainf**k language is allowed. After I solve this problem in 0.00s using BF  , I have an idea to set new BF problems, now here I come The task is simple, given a (1="length of string"=1000) just check if the string is palindrome or not. The string contains character in range ASCII(32)=char=ASCII(126) Input The first line, there is an integer T (1 ≤ T ≤ 1000) denoting number of test cases then you should process only next T  lines, each line is a terminated by new line character ('\n') ASCII(10) Output For each test case: if <string> is palindrome, output: "<string>" is palindrome else, output: "<string>" is not palindrome remember to put '\n' after each test case Example Input: 11 abba abba   abba  abba  Tjandra Satria Gunawan Tjandra Satria Gunawan nawanuG airtaS ardnajT () (( kasur ini rusak Kasur ini rusak x Don't process this case because T is 11 And also this problem use exact judge so be careful put space and '\n' Only brainf**k is allowed and soure limit is 1500 bytes Output: "abba" is palindrome "abba " is not palindrome " abba" is not palindrome " abba " is palindrome "Tjandra Satria Gunawan" is not palindrome "Tjandra Satria Gunawan nawanuG airtaS ardnajT" is palindrome "()" is not palindrome "((" is palindrome "kasur ini rusak" is palindrome "Kasur ini rusak" is not palindrome "x" is palindrome Time limit ~2x My fastest BF code If you TLE here, you may try this problem first. See also: Another problem added by Tjandra Satria Gunawan
33,077
Tic-tac-toe 3 (OVOXO) Bored to death working at the Byteland Office...your colleagues have resorted to game of crosses Xs and noughts Os or Tic-tac-toe. One of them keeps on losing and is tired of the jokes. He plans to have an Android app in his phone to help him out. He is your good friend and seeks your assistance. "Treat at ANC is guaranteed", he says. He also is very frugal when it comes to memory usage. So please don't write a long if else chain... because you have to do the task within 999 bytes. Input An integer T - the number of test cases. (T < 1000). T test cases follow. Each test case comprises 3 strings each separated by newline and containing exactly 3 characters (either 'X','O' or '_') per line. An empty line follows each test case. Each input position is guaranteed to be a valid tic-tac-toe position such that the game is still not over. Output For each test case print "WON" if it is a sure shot winning position, else print "CONTINUE". Then output the game after having made your move. If more than one move are equally good try playing the move on the first empty spot. Example Input: 2 OOX OX_ __X XX_ XOO _O_ Output: WON OOX OXX __X WON XXX XOO _O_ Info X always moves first (it is the standard) and whose move it currently is can be computed. Winning position is meant for the current player. Winning in fewer moves is better, and drawing is better than losing as in general AI. You need to print the board as it looks after making the best move. Print WON if the current player can win in the case when both players play optimally from here on.
33,078
Median of sub-sequences (KMEDIAL) Let a given sequence S (of length n) of positive integers be called x-medial (where x is a positive integer) if: n is odd, and the median of the sequence (the ((n+1)/2) th largest term) equals x. OR n is even, and both the central terms ((n/2) th largest and (n/2+1) th largest) are equal to x. Given a sequence A (of length N) of positive integers and an integer k, find out how many of its sub-sequences are k-medial. A sub-sequence of A is any sequence {A[i], A[i+1], A[i+2] ... A[j]}, where 0 ≤ i ≤ j < N. Input The first line contains T (T ≤ 15), the number of test cases. Each test case consists of 2 lines. The first line contains the numbers N (1 ≤ N ≤ 10 5 ) and k (1 ≤ k ≤ 10 9 ), separated by a single space. The next line contains the sequence A (N terms, each ≤ 10 9 , separated by single spaces between them). Output Output T lines, each containing a single integer, equal to the number of k-medial sub-sequences. Example Input: 2 3 5 17 5 2 5 2 1 2 2 3 7 Output: 2 7
33,079
WIND VANE (WINDVANE) Problem Statement: Wind vane is an instrument for showing the direction of the wind.   Dream city is in the shape of a matrix of dimensions mxn. To monitor the direction of the wind in the city, wind vanes are placed in every unit cell of the city. According to the direction of the wind, these wind vanes turn themselves. Lets assume that there are only 4 directions North, East, West and South denoted by (‘N’, ’E’, ’W’, ’S’). We know the initial direction of the wind vanes. We denote the direction of change of wind by 0 (clockwise) and 1 (anti-clockwise) Function “Change(x1, y1, x2, y2, direction)”, changes the direction of the vanes in the sub-matrix (from x1, y1 to x2, y2) in the specified ‘direction’ (for example if the initial state of a cell is ‘N’ and the direction is clockwise, then the cell changes to ‘E’) The ‘Change’ may occur any time. We need to know the direction of the wind at any unit cell at any instant. Direction (x, y) should print the direction of the vane at the cell (x, y). Input: The first line of the input consists two integers m and n - the dimensions of the city. Then follows the description of the matrix which denotes the direction of the vanes. The next line contains an integer c, the number of commands to process. Each command can be either of the format "C x1 y1 x2 y2 d" or "D x y". Output: Process the commands and print whenever necessary.   Input Constraints: 1<=m<=1000 1<=n<=1000 each character in the matrix is one among {'N','E','W', and 'S'} 1<=c<=10000 1<=x1,y1,x2,y2,x,y<=1000 d= 0(clockwise) or 1(anti-clockwise) x1<=x2 y1<=y2   Sample Input: 5 5 ESWNE NWWWN EEESE SSWSN SNWEN 5 C 2 1 4 1 1 D 3 1 D 3 3 C 2 1 5 2 0 D 3 1   Sample Output: N E E
33,080
THE N WITTY FRIENDS (WITTY) N witty friends went for an outing trip. During the outing they have spent lot of money in lot of places. In some places, a friend (A) spends ‘M’ money for his friend (B). An expense is described by "A spends M$ for B". A transaction is described by “X gives K$ to Y”. You are given all the expenses made by the friends. The outing trip is ended and now you have to find the minimum transactions to be made by the friends to tally the expenses. Input The first line consists of an integer t, the number of testcases. For each test case, the first line consists of an integer N, the number of expenses made by friends followed by N lines. Each line contains two strings A and B (A ≠ B) and an integer m, the money A spent for B. Output: For each test case, print the minimum number of transactions required to tally the expenses. Constraints 1 ≤ t ≤ 10000 1 ≤ N ≤ 10 A ≠ B Each character in A is either 'A' or 'B'. Each character in B is either 'A' or 'B'. 1 ≤ length of A, B ≤ 2 1 ≤ m ≤ 10000 Sample Input: 3 1 AA BB 10 3 A BB 100 BB AA 100 AA A 100 4 AB BA 100 BA B 100 AB B 100 B A 200 Output: 1 0 1 Explanation of Test Cases Case 1: AA spent 10$ for BB. So one transaction "BB gives 10$ to AA" is needed to tally the expense. Case 2: A spent 100$ for BB, BB spent 100$ for AA and AA spent 100$ for A. In this case, no transactions are required as the expenses are already tallied. Note: that A can spend for B at many places.
33,081
Move the boulder (BOULDER) A huge boulder is somehow blocking a public square. The citizens, each one of them approaching from his/her street, decide to remove it. Each citizen can try to either push the boulder away from him, pull it towards him, or choose to do nothing. (note that the citizens cannot change their direction relative to the boulder). Obviously, they want to remove the boulder as quickly as possible - in other words, they want to maximise the magnitude of the net force they apply. Tell them what this maximum possible magnitude is. Input The first line contains T (1 ≤ T ≤ 15), the number of test cases. For each test case, the first line contains N (1 ≤ N ≤ 10 5 ), the number of citizens. Each of the next N lines contains four integers (separated by single spaces) : The first two integers (each ≤ 10 9 ) represent the x and y components (respectively) of the direction in which the citizen would push. If he pulls, it would be in the exactly opposite direction. Note that this given "direction vector" does not necessarily have magnitude 1. However, its magnitude is indeed a meaningless quantity. The next two integers F pull  and F push (1 ≤ F pull , F push  ≤ 10 5 ) represent the magnitude of the force the citizen applies while pulling and pushing, respectively. Output For each test case, output a single decimal number, correct to 6 digits after the decimal point, representing the maximum possible magnitude of resultant force. Example Input: 2 3 1 0 5 3 -3 0 12 6 0 1 4 7 1 13 6 58 24 Output: 16.5529 58
33,082
EVEN COUNT (GEEKOUNT) Let f(x) be the product of digits of a number. Given L and R, find the number of values of 'i' such that L ≤ i ≤ R and f(i) is even . Input The first line consists of an integer t, the number of test cases. For each test case, you are given the two integers L and R. Output For each test case, print the number of values of 'i' such that L ≤ i ≤ R and f(i) is even. Constraints 1 ≤ t ≤ 100 1 ≤ L ≤ R ≤ 1000000000 Sample Input: 2 2 12 4 23 Output: 6 12
33,083
Cut on a tree (COT6) A path of rooted tree is a "straight-chain" iff for each node pair (u, v) on the path, either u is the ancestor of v, or v is the the ancestor of u. Given a rooted tree with weighted nodes, decompose it into several "straight-chain", so that the quadratic sum of all "straight-chain" is minimum. The weight of a "straight-chain" is the sum of the weights of all the nodes on this chain. Input The first line contains an integer N (N ≤ 1200000), the number of nodes. The second line contains n integers w1, w2, ... wn. wi represents ith-node's weight. The following n-1 lines, each line describes an edge of the tree. The nodes are numbered from 1 to n, and 1 is the root. Output An integer, the minimum quadratic sum. It is guaranteed that the answer will not exceed 10 14 . Example Input: 7 -4 -10 5 4 1 -1 -5 1 2 2 3 1 4 2 5 5 6 5 7 Output: 42
33,084
The new President (PRESIDEN) Finally, it is time to vote for a new president and you are really excited about that. You know that the final results may take weeks to be announced, while you can't really wait to see the results. Somehow you managed to get the preferences list for every voter (we don't care how you managed to get this piece of information!). Each voter sorted out all candidates starting by his most preferred candidate and ending with his least preferred one. When voting, a voter votes for the candidate who comes first in his preferences list. For example, if there are 5 candidates (numbered 1 to 5), and the preferences list for one voter is [3, 2, 5, 1, 4] and the current competing candidates in the voting process are candidates 2 and 4, the voter will vote for candidate number 2. Here are the rules for the election process: There are  C  candidates (numbered from 1 to  C ), and  V  voters ( V  is always an odd number). The election process consists of up to 2 rounds. All candidates compete in the the first round. If a candidate receives more than 50% of the votes, he wins, otherwise another round takes place, in which only the top 2 candidates compete for the presidency. The candidate who receives more votes than his opponent wins and becomes the new president. You can safely assume that the given preferences will never cause a situation in which the second and the third candidates from the first round receive the same number of votes. The voters' preferences are the same in both rounds, and each voter must vote exactly once in each round for a currently competing candidate according to his preferences. Given the preferences lists, you need to write a program to figure out which candidate will win and in which round. Input Your program will be tested on one or more test cases. The first line of the input will be a single integer  T , the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, the first line of a test case contains two integers  C  and  V  separated by a single space.  C  and  V  (1 ≤ C ,  V ≤ 100) represent the number of candidates and voters respectively, followed by  V  lines each line contains  C  integers separated by a single space, representing the preferences list for a single voter (the first is his most preferable candidate while the last is his least preferable one). Each integer from 1 to  C  will appear exactly once in each line. Output For each test case, print on a single line two integers separated by a single space. The first integer is the ID of the winner candidate (a number from 1 to C), the second integer is cither 1 or 2 indicating whether this candidate will win in the first round or the second one respectively. Example Input: 2 2 3 2 1 1 2 2 1 3 5 1 2 3 1 2 3 2 1 3 2 3 1 3 2 1 Output: 2 1 2 2
33,085
Manku Word (MAY99_2) Manku loves Codechef's Lucky Number and now he decided to start Manku words :) Manku words are those words which have only letters 'm', 'a', 'n', 'k', 'u'. Generally in english, 'a' comes before 'k', 'k' comes before 'm' and so on. But in Manku's dictionary, 'm' comes before 'a', 'a' comes before 'n', 'n' comes before 'k', 'k' comes before 'u'. Thus according to manku 1st manku word is m 2nd manku word is a 3rd manku word is n 4th manku word is k 5th manku word is u 6th manku word is mm 7th manku word is ma and so on ... Your task is very simple. For given value of n, write the n-th manku word. Input First line of input contains an integer t (1 <= t <= 100). Each test case contains an integer n (1 <= n <= 10^18). Output For every test case print the n-th manku word on separate line. Example Input: 5 10 4 16 17 31 Output: mu k nm na mmm
33,086
Kindergarten Painting Competition (KINDERPC) One of the most anxiously awaited occasions in any school is its annual day. Great excitement and hurried activities are visible all around. The prize-winners and those who are participating in the cultural programme are especially elated. Raheem has volunteered to help organize the event, and he’s in charge of the prize distribution ceremony for the kindergarten painting competition. Before the prizes are announced, the participants will be brought in and seated in the front row. There are N participants, and their paintings have been ranked from 1 to N by the judges (1 being the best). However, since all the entries were amazing, the judges have decided that everyone deserves a prize. So, Raheem has arranged N seats in the front row. All was well until Raheem realized that if both the neighbours of a participant (i.e. the participants sitting on the chairs adjacent to his/hers) are ranked higher than him/her, then he/she will feel inferior and start crying (after all he/she is in kindergarten!). Raheem, being a puzzle-lover, wonders how many ways there are to seat the participants in the front row, so that none of them feel inferior. More importantly, Raheem also wants to find out what is the expected number of participants who will feel inferior if they are seated randomly, so that he can have that many people ready to take care of crying kindergarteners. Notes : Two seatings are different if there is at least one chair which is occupied by different students in the two arrangements. “Seated randomly” means each arrangement is equally likely to be chosen. The participants sitting on the leftmost chair and the rightmost chair will never feel inferior, as they have only one neighbour. Input The first line contains the number of test cases T. T lines follow, one for each test case. Each line contains an integer N, denoting the number of students. Output Output one line for each test case, containing two integers. The first should be the number ways of seating the participants in the front row, so that none of them feel inferior. As this number can be very large, output it modulo 1000000007 (i.e. 10 9 + 7). The second should be the greatest integer less than or equal to the expected number of participants who will feel inferior if they are seated randomly. Constraints 0 < T < 20 0 < N < 10 9 Example Input: 2 1 3 Output : 1 0 4 0 Explanation In the second test case, there are 2 arrangements in which 1 participant (the one ranked 3rd) feels inferior, namely 132 and 231. In the other 4 arrangements, namely 123, 213, 321 and 312, none of the participants feel inferior. The expected number of participants feeling inferior is 0 × 4 / 6 + 1 × 2 / 6 = 0.33 .
33,087
Nice Binary Trees (NICEBTRE) Binary trees can sometimes be very difficult to work with. Fortunately, there is a class of trees with some really nice properties. A rooted binary tree is called “nice”, if every node is either a leaf, or has exactly two children. For example, the following tree is nice, but the following tree is not. The leaves of a nice binary tree are labeled by the letter ‘l’, and other nodes are labeled by the letter ‘n’. Given the pre-order traversal of a nice binary tree, you are required to find the depth of the tree. Notes : The depth of a tree is defined as the length of the longest path with one end at the root. The pre-order traversal of the tree in the first image above produces the string “nlnnlll”. Input The first line contains the number of test cases T. T lines follow. Each line contains a string, which represents the pre-order traversal of a “nice” binary tree. Leaves are represented by the letter ‘l’ and other nodes by the letter ‘n’. The input is guaranteed to be the preorder traversal of a nice binary tree. Output Output one line for each test case, containing a single integer, the depth of tree. Constraints 0 < T < 20 Length of the input string in each test case is at most 10000. Example Input: 3 l nlnll nlnnlll Output: 0 2 3
33,088
Easy Jug (MAY99_3) One day Manku was very thirsty so he decided to drink exactly z litres of water. However , in front of him, there is a well of infinite amount of water and 2 empty jugs of quantity x litres and y litres respectively. Now Manku can do the following operations to any jug Fill it completely from the well Empty it entirely Transfer as much water from Jug 1 to Jug 2, until Jug 1 gets empty or Jug 2 is completely filled. Now since he has no measuring device so he will do these operations only to make any of the 2 jug having exactly z litres of water. Now Your task is given value of x, y, z, tell whether it is possible for Manku to drink water or not. Input First Line of Input contains T, the number of test cases. (T <= 25) Then for each test case there are 3 numbers x, y, z given in separate line. 1 <= x <= 10^8 1 <= y <= 10^8 1 <= z <= 10^8 Output For each test case output " YES " if manku can drink exactly z litres of water else " NO ". Example Input: 5 2 4 3 2 5 1 9 3 6 3 8 7 6 1 10 Output: NO YES YES YES NO Explanation In Test case 1 Either Manku can have 2 or 4 litres of water so he cant drink 3 litres. In Test case 2 Manku can have 1 litre water by doing the following operations: Fill 2 litre Jug Transfer its water to 5 litre Jug Again Fill 2 litre Jug Again Transfer its entire water to 5 litre Jug Now 5 litre Jug will have total 4 litre water Again Fill 2 litre Jug Now transfer 1 litre water to 5 litre Jug because at present 5 litre Jug don't have space for more than 1 litre water Now the 2 litre Jug will have only 1 litre water left For Test case 3 we will transfer 3 litre water twice from 3 litre jug to 9 litre jug For test Case 4, transfer 3 times water of 3 litre jug to 8 litre jug Ultimately 3 litre Jug has 1 litre water left and 8 litre Jug is full Now empty 8 litre jug and pour remaining 1 litre of 3 litre jug in it Now fill 3 litre jug fully twice and transfer its water to 8 litre jug Now 8 litre Jug will have 7 litre water For Test case 5, we cant have 10 litre of water in any jug
33,089
Contest Hall Preparation (CONHONPR) Before the ACM-ACPC regional contest, the site director and the volunteers were very busy preparing for the contest. One of their tasks is to assign a table for each team such that no two teams from the same university are adjacent to each other. The site director decided not to waste his time doing this task and asked the judges to do it. The judges thought this could be a good problem to be used in the contest problems set. As they were very busy preparing for the contest, the judges decided to solve part of the problem and ask the contestants to solve the rest. The judges will generate a number of layouts for the teams assignment to the tables and will ask the contestants to write a program to check whether each of these layouts is valid or not. If a layout is not valid the program should count how many different universities have at least two of their teams sitting adjacent to each other. "Well, you may use those solutions for the next year's contest", said by the chief judge  Ahmed Aly  to the site director. The contest hall can be represented as a 2D grid of  N  rows with  M  cells in each row. Each cell in the grid is either occupied by a team or empty. There could be up to 8 teams adjacent to a single team. A team may have less than 8 adjacent teams if it is seated next to a hall edge or some of its adjacent cells are empty. For example, in the layout shown in the following figure, team E has 7 adjacent teams, named A, B, C, D, F, G and H, while the adjacent teams to team A are B, D and E. Input Your program will be tested on one or more test cases. The first line of the input will be a single integer  T , the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, each one starts with a line containing 2 integers separated by a single space  N  and  M  (1 ≤ N ,  M ≤ 100) representing the dimensions of the hall, followed by  N  lines each line contains  M  integers separated by a single space, representing the tables assignment in this row. Each integer represents the university ID of the team assigned to this table or ' -1 ' if it is empty. All universities IDs are positive integers not greater than 100. Output For each test case, print on a single line integer, the number of different universities having at least two of their teams adjacent to each other. Example Sample Input 3 3 3 1 2 3 2 2 2 1 1 1 3 3 1 2 3 3 -1 1 2 -1 2 3 3 1 2 3 -1 1 5 1 2 4 Sample Output 2 0 1
33,090
Rachu (MAY99_4) Rachu is very happy today because its his birthday :D and he has a birthday party at home with 'r' friends. He went to market to purchase something to eat. (He is really fond of eating :P ). At the shop he found muffins at a very reasonable price (ohh!! he loves muffins ;) ). He bought 'n' muffins from the shop. After reaching home he is wondering that in how many ways he can distribute these muffins between his friends. He shouldn't be rash so he would give at least 1 muffin to each friend. For rest of the muffins left he can distribute it in any manner. He is still wondering the number of ways in which he can distribute these muffins. Help him out by writing a code which calculates the number of ways the muffins could be distributed and print "-1" (quotes for clarity) if its impossible for him to distribute the muffins. Consider each muffin as similar. The number of ways could go very large so output the result after taking a mod with 10000007. Input The input consists of 2 integers: n - the number of muffins, and r - The number of friends. Output The required answer modulo 10000007. Constraints 1 ≤ n, r ≤ 100 Example Input: 2 1 Output: 1 Input: 4 2 Output: 3 Explanation In 1st case he has 2 muffins and called only 1 friend so he gave both the muffins to him. In 2nd case he 1st give 1 muffin each to both. Then he can give 0 muffin to 1st friend and 2 to the 2nd or 1 muffin to each or 2 muffins to 1st friend and 0 to the 2nd.
33,091
The Encrypted Password (ICPC12C) Encrypting passwords is one of the most important problems nowadays, and you trust only the encryption algorithms which you invented, and you have just made a new encryption algorithm. Given a password which consists of only lower case English letters, your algorithm encrypts this password using the following 3 steps (in this given order): Swap two different characters of the given password (you can do this step zero or more times). Append zero or more lower case English letters at the beginning of the output of step one. Append zero or more lower case English letters to the end of the output of step two. And the encrypted password is the output of step three. You have just finished implementing the above algorithm and applied it on many passwords. Now you want to make sure that there are no bugs in your implementation, so you decided to write another program which validates the output of the encryption program. Given the encrypted password and the original password, your job is to check whether the encrypted password may be the result of applying your algorithm on the original password or not. Input Your program will be tested on one or more test cases. The first line of the input will be a single integer  T , the number of test cases (1 <= T <= 100). Followed by the test cases, each test case is on two lines. The first line of each test case contains the encrypted password. The second line of each test case contains the original password. Both the encrypted password and the original password are at least 1 and at most 100,000 lower case English letters (from ' a ' to ' z '), and the length of the original password is less than or equal the length of the encrypted password. Output For each test case, print on a single line one word, ' YES ' (without the quotes) if applying the algorithm on the original password may generate the encrypted password, otherwise print ' NO ' (without the quotes). Example Input: 3 abcdef ecd cde ecd abcdef fcd Output: YES YES NO
33,092
MayanCalendar (APCER) The Maya is a Mesoamerican civilization noted for its art, architecture, mathematics and astronomical systems. In the recent past their calendar system has been quite in the news because of the misinterpretation of their Long count calendar, which gave way for a popular belief that a cataclysm will take place on December 21, 2012. Many speculated it will mark the end of human civilization! But we now know it did not happen as we are still alive! Note this date, it falls on a Friday. Since human civilization may have ended on that day, we will call every Friday the 21st as a vulnerable day. Similarly we define a safe day which is not a vulnerable day. Your task is given two years M and N, you need to find how many safe days are there between any given years M and N (inclusive). To honor the Mayan civilization you should write the total number of safe days in Mayan Long Count notation. The Long Count calendar identifies a date by counting the number of days from the Mayan creation date. But instead of using a base-10 scheme like Western numbering, the Long Count days were tallied in a modified base-20 scheme. As a matter of fact December 21, 2012 is simply the day that the calendar will go to the next B'ak'tun. You do not need to bother about creation date but simply represent your answer in Long Count notation. See the below example and table for clarification: Days Place Long Count unit 1 0 1 K'in 20 1 1 Winal 360 2 1 Tun 7,200 3 1 K'atun 144,000 4 1 B'ak'tun Table of Long Count units Check the full list here: en.wikipedia.org/wiki/Maya_calendar (not needed for this problem). Conversion For this problem you can consider numbers in the Long Count to be represented in base 20 except for the Winal place which is to be taken in base 18. Below example will clarify how to convert your answer into Long Count Notation. For instance, if safe days comes out to be 1454 your output must be: "0.0.4.0.14" (without quotes). (1*14 + 20*0 + 360*4 + 7200*0 + 144000*0 = 1454) For 360 output must be "0.0.1.0.0" (without quotes). For 20 output must be “0.0.0.1.0” (without quotes). As you can see all the places are in base 10 except the 1 st place which is base 18. Input First line of input contains 0 < T < 500, number of test cases on which your program will run. Followed by two integers M and N where 1901 <= M, N <= 2300, where M <= N, if M = N you need to tell for that particular year only. Output For every test case output: A single line containing the number of safe days between the year M and N (inclusive) in Long count notation explained above. It is guaranteed that the number of safe days could always be represented up to fourth place (B'ak'tun place) in the above given notation. "a.b.c.d.e" (without quotes) where 0 <= a, b, c, e < 20, 0 <= d < 18. Facts Jan 1, 1901 was Tuesday. All calculations must be done following Gregorian calendar which is the current standard calendar in the world including ours. If you don't know how to calculate leap year see this link: en.wikipedia.org/wiki/Leap_year Sample Input: 3 2011 2012 2012 2012 2000 2020 Output: 0.0.2.0.7 0.0.1.0.4 0.1.1.3.14 Explanation For case 1: there are 727 safe days which can be represented as 0.0.2.0.7 There are 4 vulnerable days between: January 2011 to December 2012. These are: 21 st January 2011, 21 st October 2011, 21 st September 2012 and 21st December 2012. Total number of days between: January 2011 to December 2012 are 731. Therefore the number of safe days are 731-4 = 727.
33,093
Modular Fibonacci Period (PISANO) Perhaps the first thing one notices when the Fibonacci sequence is reduced mod M is that it seems periodic. For example : F (mod 4) = 0 1 1 2 3 1 0 1 1 2 3 ... F (mod 5) = 0 1 1 2 3 0 3 3 1 4 0 4 4 3 2 0 2 2 4 1 0 1 1 2 3 ... We define K(M) the period of the Fibonacci sequence reduced mod M if it is periodic. We just saw that K(4) = 6 and K(5) = 20. Input The input begins with the number T of test cases in a single line. In each of the next T lines there are one integer M. Output For each test case, on a single line, print K(M), or "Not periodic." without quotes if need. Example Input: 3 4 5 6 Output: 6 20 24 Constraints 1 < T < 10^4 1 < M < 10^12 Edit 2017-02-11, after compiler changes ; new TL. My old Python code end in 1.92s.
33,094
Fimodacci (FMODF) After solving Fib-Factorization and ModFib-Period , you would probably be interested by solving this new task: Simply compute Fib(N) mod Fib(K), where Fib(N) denotes the Nth term of the Fibonacci sequence. (If N<2 Fib(N)=N, else Fib(N)=Fib(N-1)+F(N-2)). Input The input begins with the number T of test cases in a single line. In each of the next T lines there are two integers N, K. Output For each test case, on a single line, print Fib(N) mod Fib(K). Example Input: 2 5 5 13 5 Output: 0 3 Constraints 1 < T < 10^5 1 < N < 10^18 1 < K <= 10^3 Edit(2017-02-11) : New time limit (after compiler changes).
33,095
Counting Lucky Numbers (CNT_LUCK) Find out how many numbers between a and b (inclusive) when represented as binary numbers have sum of digits lucky. A number is lucky if its decimal representation contains digits 4 and 7 only. eg. 4, 7, 47, 77 etc. where as 14, 41 etc. are not. Note that 0 <= a <= b <= 10^19. Input T: number of test cases T<=10^5 Next T lines have a and b in every line. a <= b Output for every test case output as described in problem statement Example Input: 2 15 15 63 63 Output: 1 0
33,096
Crayon (CRAYON) Background Mary love painting so much, but as we know she can't draw very well. There is no one appreciate her works, so she come up with a puzzle with herself... Description There are only one case in each input file, the first line is a integer N (N <= 1,000,00) denoted the total operations executed by Mary. Then following N lines, each line is one of the folling operations. D L R: draw a segment [L, R], 1 <= L <= R <= 1,000,000,000 C I: clear the ith added segment. It’s guaranteed that the every added segment will be cleared only once. Q L R: query the number of segment sharing at least a common point with interval [L, R]. 1 <= L <= R <= 1,000,000,000. Input n (then following n operations ... ) Output (for each query, print the result on a single line ... ) Example Input: 6 D 1 3 D 2 4 Q 2 3 D 2 4 C 2 Q 2 3 Output: 2 2
33,097
FOREVER ALONE (ALONE) Numbers can be classified as IAR numbers and FA numbers. Numbers in which all digits are equal to either adjacent digit are called In-A-Relationship numbers. For example: 11, 22, 111, 9922888 and 777788822 are IAR numbers. Numbers featuring lonely digits are called Forever-Alone (FA) numbers. For example: in 22122 digit 1 is alone and in 123 all digits are alone. Given K, your task is to find the Kth In-A-Relationship (IAR) number. Input The first line contains number of test cases T (T ≤ 50) Then T test cases follow. Each line contains one integer K (1 ≤ K ≤ 5×10 6 ) Output For each test case, print the Kth IAR number. Sample Input: 5 1 2 3 10 12 output: 11 22 33 111 333
33,098
Discord is at it again (PONY8) Princess Celestia has allowed Discord to be released in order to reform him. Discord, of course, does not wish to be reformed. While loose, he secretly destroyed all of Twilight Sparkle's books on reforming spells. But only the books. The information is still there, locked behind his chaotic magic. His chaotic magic created what is known as Mega String. To create this string, start by writing down the numbers 1, 2, 3, ..., and so on, and do this without putting any space between the numbers or digits. So it would look like this: 12345678910111213141516.... However, for some reason, at that time, chaos dislikes the number 5. So any number that contains 5 as a digit, anywhere, isn't included in the Mega String. So the real Mega String looks like this: 1234678910111213141617... and much later it looks like this: .., 47, 48, 49, ... ...474849606162... The question Twilight Sparkle needs to answer is, what is the digit that is at index K in the Mega String? Make sure to answer quickly, or else the information hidden by the Mega String will surely be lost to Twilight Sparkle. The Mega String is 0-indexed. Input format: The first line is an integer T, which is the number of test cases to follow. The following T, line i+1 will contain an integer K i . Output format: T lines are to be output, and on line i should be the digit at index K i in the Mega String. Sample Input: 5 0 1 2 3 4 Sample Output: 1 2 3 4 6 Limits: 1 ≤ T ≤ 10 5 and 0 ≤ K i ≤ 10 18 Time: ×5 my fastest Java solution. Warning: Big Input Files
33,099