task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
HQNP Incomputable Hard (HQNP2) See problem HQNP for description. Score : Score is number of test cases correctly solved. Limits Any HQ0-9+−INCOMPUTABLE?! program (output for each case) must be at most 20,000 commands long. The accumulator is unbounded (it can store an arbitrarily large integer). After each command, the buffer must be at most 20,000 characters long. To prevent code injection vulnerabilities, during the execution of your program( output for each case ) the buffer must never contain non-alphanumeric characters , i.e. characters other than A-Z , a-z , and 0-9 . If it happens, your score for that particular test case will be 0. Additionally for this challenge you must use the command '+' at least once for each test case. Input First line has integer T i.e. number of test cases. ( T <= 1000 ). Next T lines has a number n ( 0 <= n <= 10^1000 ). Output For each n, output the required HQ0-9+−INCOMPUTABLE?! program( having '+' at least once ) which will give n as output. If there are multiple solutions, output any one of them. Output of each test case must be in a single line. If you don't want to solve a test case, leave a blank line for it. PS : Number of test cases in 11 test files are respectively -> 10, 10, 100, 1000, 80, 20, 40, 500, 100, 50, 200 Update (Dec/5/2012) : A small bug in judge which was causing internal error has been fixed. With refinement in test files, all solutions have been rejudged.
34,700
Find all independent nodes (INDISET) Let G be a graph with a set of n nodes and a set of  m edges. An independent set I is a subset of nodes, no two nodes of which are connected by any edge in G . A maximal independent set is an independent set such that adding any other node to the set forces the set to contain at least two nodes connected by an edge in G . In this task, you are given a undirected graph as the input, and you have to find as many as possible independent nodes within the time limit. Your score is the total number of independent nodes found in all test cases. Input The first line contains two integers, n and m , representing the numbers of nodes and edges in the graph. 3  ≤ n ≤ 2000 and 3 ≤ m ≤ 40000. The nodes are numbered 1.. n , but not necessarily in any order. The next m lines contain pair of integers representing edges between two nodes. The list of edges are not in any particular order. Output There should be one line output listing all valid independent nodes you found in the graph. The nodes are separated by one space. Example Input: 6 7 1 2 1 5 2 3 2 5 3 4 3 6 5 6 Output: 1 4 6
34,701
Find New SPOJ Problems (FINDPROB) After solving several problems on SPOJ you quickly browse to the ranking page to look at all the competitors you have overtaken. While looking at their account pages you see lots of new problems. It is too hard to remember all the problem names, so you must write a script that generates a lists of new problems for you to solve. Input The input begins with the HTML source of your SPOJ account page. The following line contains a number (C<100), which represents the number of SPOJ competitors to consider. The remainder of the input consists of the HTML source of the (C) competitors' account pages. Output Print a list of problem codes you have not yet attempted that a competitor has solved. Sort the list by the number of competitors that have solved the problem, then alphabetically to break ties. Example Input: Preview Output: Preview Score Your CPU is old and can only store 512 characters. Minimize your source length.
34,702
EASY MATH (Challenge) (EASYMATC) You will be given 4 numbers: n m a d. find count of numbers between n and m (inclusive) not divisible by (a) or (a+d) or (a+2d) or (a+3d) or (a+4d). Input first line has number t - number of test cases. each test case has 4 numbers n m a d. Output Single line having single number giving the count. Constraints 1 <= n <= m <= 2^32 1 <= a <= 2^32 1 <= d <= 2^32 2 <= t <= 100 Example Input: 3 1 10 2 2 20 100 3 3 100 1000 4 5 Output: 5 54 543
34,703
Aritho-geometric Series (AGS) (Challenge) (AGSCHALL) Arithmetic and geometric Progressions are 2 of the well known progressions in maths. Arithmetic progression(AP) is a set in which the difference between 2 numbers in constant. for eg, 1,3,5,7,9 .... In this series the difference between 2 numbers is 2. Geometric progression(GP) is a set in which the ratio of 2 consecutive numbers is same. for eg, 1,2,4,8,16.... In this the ratio of the numbers is 2. ..... What if there is a series in which we multiply a(n) by 'r' to get a(n+1) and then add 'd' to a(n+1) to get a(n+2)... For eg .. lets say d=1 and r=2 and a(1) = 1.. series would be 1,2,4,5,10,11,22,23,46,47,94,95,190 ...... We add d to a(1) and then multiply a(2) with r and so on ....   Your task is, given 'a' , 'd'  &  'r' to find the a(n) term . since the numbers can be very large , you are required to print the numbers modulo 'mod' - mod will be supplied int the test case. Input first line of input will have number 't' indicating the number of test cases. each of the test cases will have 2 lines firts line will have 3 numbers 'a' ,'d'  and   'r' 2nd line will have 2 numbers 'n' & 'mod' a- first term of the AGS d-the difference element r - the ratio element n- nth term required to be found mod- need to print the result modulo mod Output For each test case print "a(n)%mod" in a separate line. Example Input: 2 1 1 2 13 7 2 2 2 10 8   Output: 1 6 Description - for the first test case the series is 1,2,4,5,10,11,22,23,46,47,94,95,190.. 13th term is 190 and 190%7 = 1 Note - the value of a , d , r , n & mod will be less than 10^8 and more than 0. for every series 2nd term will be a+d and third term will be (a+d)*r .. and so on ..
34,704
Fun with Fibonacci Series (Challenge) (FIBFUNCH) Fibonacci series is a series in which every element is sum of previous 2 elements. first 2elements are 0,1 and the series goes like 0,1,1,2,3,5,8,13 ........   What if you were given 2 random numbers as the starting of the series and u follow the same rule as the Fibonacci rule. for eg. if you were given 2 and 2 .. the series would become 2 2 4 6 10 16 26 .........   Now your task is simple ... You will be given 2 numbers a & b .. the first and second term of the series.. you need to calculate the sum of first n numbers of the series so formed.. Since the numbers can be big you need to print the result mod some number 'M' provided in the input. Input first line will have single number 't' - number of test cases. each test case will have 4 numbers a,b,n & M a- first number of the series b- second number of the series n- calculate the sum till n numbers M- print the result mod M Output single number for each case - sum of n terms mod M Example Input: 2 2 2 10 21 1 3 10 21   Output: 13 4 Explanation - for first case series is 2 2 4 6 10 16 26 42 68 110 .. Sum is 286.. o/p = 286%21 = 13 NOTE - Number of test cases <=100. 0 <= a,b<= 10^8 1 <= n,m <= 10^8 actually n ranges from 1 to 10^8
34,705
Real Roots (REALROOT) In this problem you are challenged to factor the real roots of polynomials. You are rewarded points based on the number of testcases you solve. Input The first line contains the number of test cases, T . The first line of each test case contains an integer N , the number of coeficients. The second line contains the polynomial coeficients a N-1 , ..., a 1 , a 0  such that ( P(x) = a N-1 x N-1  + ... + a 1 x 1  + a 0 x 0 ). Output The roots of the polynomial, in sorted order. That is all real numbers  r 0 , r 1 , r 2 , ...  such that P(r) = 0 . Constrains T ≤ 20 N ≤ 20 All coeficients are in the inclusive range [-10 6 ,10 6 ] The output precision must be at least 2 decimal digits The roots must truly be real. No complex roots even if the imaginative part is very small. Cases Same as the example ~3  random integer roots ~15 random integer roots ~10 Random interger coefficients ~10 Random floating point roots ~10 Random floating point coefficients Polynomials on the form p 0 =x, p k+1 =(p k -a k )^2  e.g. ((x-3)^2-1)^2 Example Input: 4 3 1 0 -2 x 2 - 2 3 1 0 1 x 2 + 1 4 -1 3 -3 1 -x 3 + 3x 2 - 3x + 1 7 1 -1 -9 13 8 -12 0 x 6 - x 5 - 9x 4 + 13x 3 + 8x 2 - 12x Output: -1.414214 1.4142135 -sqrt(2), sqrt(2) No real roots 1 1 1 Triple root in x=1 -3 -1 0 1 2 2 Mixed integer roots Notes All testcases are double checked using Mathematica with 30 digits of precision. Constrains are set such that most approaches should be fine using double working precision.
34,706
The dojo s corridor (M5TILE) Leo is training his martial arts in byteland's dojo. There is a rectangular (5 × 2n) corridor to join the dojo. In how many ways W(n) can we exactly cover the corridor with 5n tatamis (2 × 1) ? Input There's no input for this task Output You should output 17 lines with: W(1), W(2), W(3), ..., W(17) Example Output: 8 95 ... (15 lines follows) Score Score is source length, you have to use less than 190 bytes, the third should be enough. Information W(17) fit in a 64bit signed container, W(18) doesn't. You may try M3TILE or M4TILE first. After that, you may try those : Tiling a WxH Grid With Dominoes , Corridor I , Corridor II .
34,707
Sum the Series (SUMUP) Nilendu is a brilliant student of Mathematics and always scores A+ in it. His professor RamjiLal is quite impressed seeing his mathematical skills and asks him to sum the following series: 1/3 + 2/21 + 3/91 + 4/273 + ..... But the fact is Nilendu is quite lazy to do his assignment. He has to watch a film and many other activities to do. So he asks you for your help. Will you be able to solve it ?? Input Input consists of t (number of test cases), then t line follows, each containing an integer N (1 <= N <= 10,000). Output A single line containing the sum upto Nth integer (rounded upto 5 digits) Example Input: 5 1 2 3 4 5   Output: 0.33333 0.42857 0.46154 0.47619 0.48387 Edit: The score is your source length. The smaller your code is, the more point you will get. All the solutions have been rejudged !!!
34,708
Size Contest!!!Reloaded!! (JH1) After seeing the popularity of the question size contest, Aradhya  thought of adding its new version. The problem statement is really simple. You are given 'n' and and then next n lines contain 'n' numbers.You have to calculate p and q. 'p' is the sum of numbers at even places ,but we add them only if they are positive. 'q' is the sum of numbers at odd places,but we add them only when they are negative. Then you need to find the absolute value of p and q. If p is greater  than q or equal to q,then print "Some Mirrors Lie!".  ( without quotes ) If q is greater than p, then print "Every Girl Lies!" ( without quotes ) Input First line contains a integer t=number of test cases. Then each test case contains a number n. and next line conatin 'n' numbers separated by a space. 1<=n<=100 and the numbers are less than 10^18 Output A single line for each test case as described above. Example Input: 1 5 -1 2 -3 5 -4 Output: Every Girl Lies! Mind you---> The less your fingers work .The more you GAIN!!! Note -- > Source Limit is made a little strict !! .. So chill out !!
34,709
Cartesian Shortest Path (CSPATH) The task is simple, on the 2D cartesian coordinate system, how many different shortest path from point O(0,0) to point A(x,y), but not through point B(x1,y1) and C(x2,y2). Score is the length of your source. Input The first line is an integer  T (1 ≤  T  ≤ 10000), denoting the number of test cases. Then,  T  test cases follow. Each test case consist of 3 lines: -first line contains two integer x  and y (1 ≤ x , y  ≤ 10) location of point A -second line contains two integer x1 (0 ≤ x1  < x) and y1 (1 ≤ y1  ≤ y) location of point B -third line contains two integer  x2 (1 ≤  x2  ≤ x) and  y2 (0 ≤  y2  < y) location of point C Output For each test case, output number of different shortest path from (0,0) to point A but not through point B and C. Example Input: 2 4 5 3 4 2 2 3 3 2 1 1 2 Output: 32 2   See also: Another problem added by Tjandra Satria Gunawan
34,710
Tiling a WxH Grid With Dominoes (MNTILE) Write a program that takes as input the width, W and height H of the grid and outputs the number of different ways to tile a W-by-H grid with (2x1) dominoes. Score is the length of your source. Input The first line is an integer  T (1 ≤  T  ≤ 276), denoting the number of test cases. Then,  T  test cases follow. For each test case, there are two integers W  and H (0 ≤ W + H  ≤ 22) written in one line, separated by space. Output For each test case, output the number of different ways to tile a W-by-H grid with (2x1) dominoes. Example Input: 6 1 2 2 3 3 4 4 5 5 6 6 7 Output: 1 3 11 95 1183 31529 Information All outputs will fit on 64-bit signed integer and less than 10 15 . You may try M3TILE , M4TILE , or M5TILE first.   See also: Another problem added by Tjandra Satria Gunawan
34,711
A Very Easy Problem! (Challenge Mode) (EPROBLEM) This is challenge version of A Very Easy Problem! . Given integer i , Your task is   to convert integer i into http://www.spoj.com/problems/EASYPROB/  format. Score is the length of your source. Input There are multiple test cases, each line contain an integer i (0 <  i  < 2 64 ). Process input until EOF. Output For each case, output the converted number in separate line. Example Input: 137 1315 Output: 137=2(2(2)+2+2(0))+2(2+2(0))+2(0) 1315=2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)   See also: Another problem added by Tjandra Satria Gunawan
34,712
PIEK (PIEK2) Ms. Magda likes cookies very much. In the summer she decided to organise an expedition which purpose is to taste wares from each bakery. Our heroine has been thinking about finding as minimal as possible lenght of the track which passes through each bakery exactly once and returns do the start point. She managed to get the table of distances beetween every two bakeries. You, as a good friend of Magda, decided to help her with the problem and here is our purpose: you have to write a program, which calculates a minimal lenght of the track in exchange for cookies. The shorter your track is, the more cookies you get and Magda is more satisfacted. Don't dissapoint her, she's pretty hot.   Example   We've got 4 bakeries: 1,2,3,4 . The table of distances looks as follows: 1 2 3 4 1 0 4 7 3 2 4 0 5 8 3 7 5 0 6 4 3 8 6 0 The shortest lenght equals to: 18 . An example way how the track may look: 1->4->3->2->1 Input In the first line the number of bakeries (n). Next follow n lines, each consisted of n numbers (which are the distances beetween bakeries). Output In the first line the calculated lenght of your track. In the second line n+1 numbers separated by whitespaces (from 1 to n including) where the first and the last have to be the same, it's the order of visiting bakeries. n<=400 Example Input: 4 0 4 7 3 4 0 5 8 7 5 0 6 3 8 6 0 Output: 18 1 4 3 2 1 Score: It's the number of cookies that Magda gives to you, she gives more if the track is shorter.
34,713
Enigma Machine (ENIGMAS) This challenge is to simulate the three rotor M3 Enigma Machine. For each test three lines of information will be provided; the first line will contain the rotor settings, the second the plugboard, and the third will be the text to encode/decode with the Enigma cipher. Input The first line will contain a single value T, for the number of tests to follow, where T <= 100. For each test there will be three lines: The first line will contain three entries indiciating: the Walzenlage, the Ringstellung,  and the Grundstellung in the form '123 AAA BBB'. The Walzenlage  only contains numbers 1-5. The Ringstellung  and Grundstellung  will be provided as triplets of letters in the range A-Z. The second line will contain pairs of letters, from the range A-Z, indicating the settings for the Steckerbrett  - there may be up to 13 pairs of letters. The final line of the test will contain an unknown length message to encode/decode - the message will be in the standard quintuple form used at the time, separated with spaces, eg 'ABCDE FGHIJ KL'. The final group may be 1-5 letters in length. Again, only the range of letters A-Z will be used. The line will be terminated in a newline ('0x0A'). The Enigma machine used is the three rotor M3 version. This had five rotors, of which only three would have been installed at any time. The Umkehrwalze  in use is the 'B' wiring. Output The output is to match the third line of the input, i.e. must be in the same quintuple grouping. One line of output per message is to be produced. Example Input: 2 123 JAN DER 2 123 JAN DER SP OJ RU LZ THISX ISXAN XEXAM PLEXI NPUT 543 SPO JPL SH OR TE NI YUQKD YVPSF HCQEI VHAPE NAQZQ I SP OJ RU LZ YUQKD YVPSF HCQEI VHAPE NAQZQ I Output: SJLKM SVZYM HXTUW VVWYY EDEB THISX ISXAX DECOD XEDXM ESSAG E
34,714
Strongly Connected Chemicals (SCCHEM) One type of chemical compounds is the ionic compound, because it is composed of positively charged ions (cations) and negatively charged ions (anions) in such a way that the compound as a whole is electrically neutral. Cations always attract anions and anions always attract cations. Now you are given m cations and n anions, and their connectivity information about which cation attracts which anion. You task is to find a sub group from the cations and anions where there is at least one cation and at least one anion, such that all the cations in the group attract all the anions in the group. We call such a group as 'Strongly Connected Chemicals' . As there can be many such groups, we want to find a group which has the highest cardinality. Cardinality means the number of members (cation and anion) in the group. Input Input starts with an integer T ( ≤ 100) , denoting the number of test cases. Each case starts with a line containing two integers: m and n (1 ≤ m, n ≤ 50) . Each of the next m lines contains n characters (without space), each either '0' or '1' . If the j th character in the i th line is 1 , that means the i th cation attracts the j th anion, otherwise it doesn't. Output For each case, print the case number and the maximum possible size of the strongly connected chemical group. Sample Input Output for Sample Input 2 3 4 1100 1110 0011 2 2 10 00 Case 1: 4 Case 2: 2
34,715
Minimum knight moves Challenge (NAKANJC) Anjali and Nakul are good friends. They had quarrelled and you had written a program for Anjali to know the  minimum number of moves a knight takes to reach from one square to another square of a chess board  (8X8).  Nakul is brilliant and knows Anjali didn't write it herself and says her program is too slow by all standards. He is  unimpressed so she asks you to try solve the problem faster this time using as few keystrokes as possible. She wants to know whether you can actually do it. Anjali is very weak in programming. Help her to solve the  problem.  Since you are busy and tend to forget she reminds you that "A knight can move in the shape of an "L" in a chessboard - two squares either forward, backward, left, or right and then one square to its left or right. A knight move is valid if it moves as mentioned above and it is within the boundary of the chessboard (8 X 8).  Since you are busy and tend to forget she reminds you that- "A knight can move in the shape of an "L" in a chessboard - two squares either forward, backward, left, or right and then one square to its left or right. A knight move is valid if it moves as mentioned above and it is within the boundary of the chessboard (8 X 8)." first solve problem  http://www.spoj.com/problems/NAKANJ/ Input There are T test cases in total. The next T lines contain two strings (start and destination) separated by a  space. T<= 200001 The strings start and destination will only contain two characters - First character is an alphabet between  'a' and 'h' (inclusive), Second character is a digit between '1' and '8' (inclusive) - (Quotes just for clarity). Output Print the minimum number of moves a knight takes to reach from start to destination in a separate line. Example Input: 3 a1 h8 a1 c2 h8 c3 Output: 6 1 4 Score: Your source code length (if you are successful in avoiding TLE and WA) The smaller code the better EDIT: Time limit increased 28-11-2012. All submissions rejudged
34,716
Pell Fourth (PELLFOUR) The double palindrome, or Quarter Pell Art Leo was quietly fighting with XerK along the East-coast with 300 friends, when XerK proposed Leo a beer, it was a Pell-Fourth. Then XerK told Leo he had a good problem found in an ancient book : -- D is a given positive integer, consider the equation : X² = D×Y² + 1, with X and Y positive integers. Find the minimum number X within all solutions. Sometimes it's possible, sometimes not! Examples : If D=2, 3² = 2×2² + 1, so X=3. If D=3, 2² = 3×1² + 1, so X=2. If D=4, it's impossible! -- Leo said that he very well knows this problem and claimed that there is yet on SPOJ a classic edition and surely others related ones. But XerK told him he had an army of byteland's computer that gave him the list of the worst test cases for D. This list begins with 2, 5, 10, ... First examples are: D X 2 3 5 9 10 19 where each new line is the minimal D to break a new record for X. E.g : for any D in [5, 10[, X(D) will be not greater than 9; and X(10) is greater than 9. The search and print of those 'pell-fect' (D, X) is the goal of this challenge. Input There's no input for this challenge. Output Start with D=2 and X=3, and print consecutive 'pell-fect' "D X" of this sequence. As the answer X could be a huge number, print instead CHK(X, 2^16384) , this only affect X numbers on line 127 and after. Example Output: 2 3 5 9 10 19 [...] constraints This is madness, but XerK can judge 1000 lines. (Edit 12/II/2017 : the MasterJudge take time into account if all 1000 lines are given.) Score If you can output n lines, XerK decided that the fairest score was exp(sqrt(n)), but he didn't want to tell why, so it was decided to set the score at 'just' n. You need to output more than 44 lines to get accepted.
34,717
Man of Steel (MOS) Clark Kent is a young journalist who was born Kal-El on the alien planet before being rocketed to Earth as an infant by his scientist father Jor-El, moments before the planet's destruction and adopted as a child by Jonathan and Martha Kent. Raised with the values of his adoptive parents, he feels alienated because of his unique super human abilities. Before the alien planet's destruction Jor-EL was killed by Dru-Zod( also known as General Zod ). Zod was sentenced to exile to the prison of Phantom Zone for his attempts to overtake the planet. Zod somehow managed to escape from his prison and now wants to kill the son of Jor-El i.e. Clark Kent. Now, Zod has reprogrammed the robot army guarding Phantom Zone and is planning to attack Earth starting with the city of Metropolis.  Fortunately, CAELOSS ( group of activists that employ electronic communication and super science cybernetics ) issued a warning for the Zod's upcoming attack to the Metropolis citizens. CAELOSS also found that Zod's Robots will be attacking the buildings such that pairwise distance of all buildings under attack is minimum. Clark after getting the information decided to defend his city and himself but he is unable to solve this complex problem of getting the Robot's attack configuration. To make an effective defence startegy he wants someone to give the best approximate result. No two Robot's will attack the same building. Pairwise distance in set of N points is defined as : ∑[ distance( A, B) ] for all distinct pairs (A,B) where A and B are points in given set. Pair (A,B) is same as (B,A). distance(A,B) = sqrt[ (A.x-B.x) 2 + (A.y-B.y) 2 ] Input First line : T ( No of test cases ) <= 20. Each test case starts with N and K i.e. number of buildings in Metropolis and number of Zod's Robots respectively. Next N lines have two integers i.e. x and y coordinates of each building. 3 <= N <= 10^5 and  2 <= K <= minimum(N, 1000) and ( 0 <= x <= 10^6, 0 <= y <= 10^6 ) and T*N <= 2*10^5 Output For each test case output "Save" K and then K lines, each having index of the building in the input ( see example ). It is obvious but stating it explicitly that for each test case: =>each building index in output should lie in range [1,N] . =>output should have exactly k distinct building indices. Otherwise solution will be judged as wrong.   Example Input: 2 4 3 0 0 0 1 1 1 2 2 3 2 1 1 1 2 9 9 Output: Save 3 1 2 4 Save 2 1 2 Score : Average of S/A over all test cases. [ minimize the score ] S = sum of pairwise distance of buildings in output. A = average distance of buildings in input from (0,0). Score for the first test case = [pairwise distance between A(0,0), B(0,1), C(2,2)]/1.3106... i.e [distance(A,B) + distance(B,C) + distance(C,A) ]/1.3106...
34,718
Wow Square (WOW_SQR) "Wow Square" This problem is about the perfect square number, given a positive integer  n   your task is to find two integers  x  and y  that satisfy: 1) x < y ≤ n . Remember that x  is always less than y . 2) x * y is a perfect square. This means that there's a positive integer z such that z * z = a * b . 3) x * y  is maximum. Find x * y as large as possible without violating previous rules. 4*) y - x  is maximum. If there still multiple solution x , y  that satisfy all previous rules, choose x , y  with largest  y - x . Input First line, there's an integer T (1 ≤ T  ≤ 10,000) then T  cases follow. Each test case there's an integer n (4 ≤ n  ≤ 10,000,000). Output For each test case, output x  and y  with this fotmat: x * y . see the examples for more detail. Example Input: 6 4 10 15 20 321 1020 Output: 1*4 4*9 3*12 8*18 245*320 864*1014 Score is length of your code. See also: Another problem added ' and recommended (new!) ' by Tjandra Satria Gunawan
34,719
"If Equal" in BF (TSET) your task is simple... you will read tow numbers a,b then print 1 if a==b or print 0 if a!=b a and b are one_digit_numbers  {0,1,2,3,4,5,6,7,8,9}. NOTE : The Only Available language For This Problem Is BrainF*** . Input there are 10 test cases ... in each one there is: one_digit_number a followed by space then one_digit_number b followed by end_of_line charachter Output the logic value of a==b Example Input: 4 7 8 8 9 7 0 1 .. Output: 0 1 0 0 .. Score is your Code Length.
34,720
"If Bigger than" in BF (BFBIGTHN) Brainf*** is a Turing complete language... what ever the arithmatic/logic operation other langs like C or LISP can do ...BF can do it also ! your task is to write a BF code to test if a is Bigger Than b .. Input: tow_digit_number t (number of test cases)followed by end_of_line charachter then t lines each of them contains:     tow_digit_number a     followed by space     then tow_digit_number b     followed by ASCII(10) (End of line). (at the end of the file there is EOF charachter which value is (-1)) output: the logic value of (a > b) for each test case (don't forget to print any space after each output such like '\n' or '\t' or space' ') Example: inputs: 09 41 92 99 40 01 20 23 00 00 01 20 30 00 09 99 00 11 12 outputs: 0 1 0 1 0 0 0 1 0      BE CAREFUL: ONLY BRAINF*** AVAILABLE FOR SUBMIT .      ENJOY ;) Note : maybe it will be helpful for you to know that a never equal to b in the test cases ;)
34,721
Good (GOV02) The problem is very easy. You are given n terms ( the terms can be integer as well as floating ). Let S = sum of all the n terms. A number k (x<=k<=y) is said to be good if S is divisible by it. Input Input begins with an integer t. Then t test cases follow. For each test case, three numbers n,x,y are given. Then n terms of the sequence follow. (REMEMBER: all the input is on a single line) Output For each test case, You have to output a single integer m. where, m = (sum of all even good numbers) - ( number of all odd good numbers) (REMEMBER: all the output should be on a single line) The numbers should be separated by spaces. Example Input: 2 3 1 2 1 2 3 4 1 10.5 -1 4.5 4.5 4 Output: 1 10 Scoring: Your task is to minimise the source code length. The less your fingers work, more you gain. Remember: Only python 2.7 is permitted.  Sorry in advance, I will not allow any other language. Source limit is tight. So be careful. Constraints: 1<=t<=10 1<=n<=100 -100<=any term of sequence<=100 0<x<=y<=100
34,722
"a mod b" in BF (BFMODULO) your task is simple ..find the answer of a mod b as fast as you can. a and b are integers 0<=a<1000 and 0<b<10 Input: integer a with leading zeroes then space ASCII(32) then b .. and EndOfLine ASCII(10)   output: the value of(a mod b)   Example1: input: 999 2 output: 1     Example2: input: 005 6 output: 5 Example3: input: 099 1 output: 0 Score:   Sometimes I enjoy writing lots of '+' in my code .. but sometimes I prefer some thing like ++++[->++++<] to shorten it. But With This New Judge, the first way is shorter. This New BF_OPERTIONS_COUNTER counts how many BFoperations your implemintaion do .. example.. code1  :  +++++++++++++++. code2  :  +++[->+++++<]>. as you see LengthOfcode2< LengthOfcode1 But .. the judge look at code2 like this: +++[->+++++<]->+++++<]->+++++<]>. and It will count these operators : '+','-','<','>' only so : code1 will have score of 15 and code2 will have score of 28 Score is "how many '+','-','>','<' your code does at the run time" BUT: since there is many test files ... and your code may expand or shorten as the judge see it .. So the final Score will be your scores average ... Thanks for Tjandra Satria Gunawan for his suggestion for the new judge .   note: you can see how the judge read your code at your submission info (only the first test file). LAST UPDATE NOTE 15/1/2012: I've complete improving test files ... there is now 59 test files ,also now you can write  100,000 byte code after solving the problem,maybe you can see that MCLT : MORE CODE --> LESS TIME Enjoy :)
34,723
The BrainFast Processing! Challenge version (FAST_BF2) 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 <string>(1≤"length of string"≤10) just check if the string is palindrome or not. The string contains character in range ASCII(97)≤char≤ASCII(122) (lower case alphabet) Input The first line, there is an integer T (1≤ T ≤100) denoting number of test cases then you should process only next T  lines, each line is a <string> terminated by new line character ('\n') ASCII(10) Output For each test case: if <string> is palindrome, output: YES else, output: NO Example Input: 2 aba ab Output: YES NO Score Score is length of your source. If you TLE here, you may try  this problem  first. If you got AC in 0.00s there you shoud got AC in 0.00s here too See also: Another problem added by Tjandra Satria Gunawan
34,724
TWO KINGS (CONQUER) Triviador is a war between two Kings. A king can attack an enemy region at each step. When a king attacks a region, he conquers all the enemy regions connected to it ( not just the immediate neighbours ). Every region is connected to all the regions that share an edge or a corner with it. The kings get alternate chances to attack. King1 gets the chance to attack first. Assume both kings are intelligent and find who will conquer the whole territory at the end of the war. It can be proved that one of the kings can win for sure if he is intelligent! Input The first line consists of an integer t, which denotes the number of test cases. For each test case the first line consists of three integers a, b, c denoting the dimensions of the territory (each cell is a region). Then the description of each cell follows. Every region contains a character ‘X’ if it is owned by King1 or ‘O’ otherwise. The description of the a×b×c 3D matrix is represented by 'a' b×c 2D matrixes. Output For each test case output the result in a single line ‘X’ if King1 wins or ‘O’ if King2 wins. Constraints 1 ≤ t ≤ 50 1 ≤ a, b, c ≤ 50 Example Input: 3 2 3 5 OXOOO OOXXX XXXXO         <- empty line just for clarity. XOXOO XOOXO OXXOX 1 1 6 OXOXXO 1 1 3 OOO Output: X O O Explanation Case 1: King 1 wins in his first move by attacking any enemy region. Case 2: King 2 can win if he is intelligent. Case 3: King 2 already won. Try: the 1D version of this problem : QWERTY04 . the 2D version of this problem : TWOKINGS .
34,725
Fibonacci factorization (BMS1988) The Mysterious Affair at Byte Court Hercule was quietly on hollydays (Noël) at Byte Court when Fibonacci and Lucas (well-dressed) knocked at his door. They came in, and the first one said : "Monsieur, can you factorise my first 1001 terms, please?". Hercule said : "It was useless to come in to ask that, but since you are here, I'll do that very quickly." Then Lucas said : "It's not a speed challenge, we like Styles too, the shorter your code is, the best your score is." Output You have to output 1001 lines, the factorization of the 1001 first terms of the Fibonacci sequence. See sample for output details. Example F(0)= 0 F(1)= 1 F(2)= 1 F(3)= 2 F(4)= 3 F(5)= 5 F(6)= 2^3 F(7)= 13 F(8)= 3 * 7 F(9)= 2 * 17 F(10)= 5 * 11 F(11)= 89 F(12)= 2^4 * 3^2 [...] F(1000)= 3 * 5^3 * 7 * 11 [...]
34,726
64bit-Fibonacci (FIB64) Warning This task is intended to help people to debug their codes and try speed experiments. The task is the same as in some known problems, but with new constraints and speed goal. The Fibonacci sequence is defined for any positive integer by : If N<2: Fib(N)=N, else Fib(N)=Fib(N-1)+Fib(N-2) You have the task of being the fastest to compute Fib(N) mod M. Input The input consists of 500,000 lines. In each the 500,000 lines there are two integers N, M. You don't need to read the whole input, only some lines to get some points. You should begin with one line, then 10, then 100, ... Output For as many test cases you can, on a single line, print Fib(N) mod M. Example Input: 5 4 5 5 5 6 [...] Output: 1 0 5 Constraints 0 <= N <= 10^18 2 <= M <= 10^18 Score As in the example, if you can output the 3 first correct answers, your score will be 3 points. No need to solve all the input, the minimum is 1 ; every solver in any language will be able to check his FIB64-speed.
34,727
The SPP constant challenge (SPPC) Warning This task can be 'easily' solved with a O(log(N)) algorithm. You'll have to work on the constant to get more points. This task should help you to try some speed improvements for problems like SPP , Snaky Numbers , or Crack the Safe which share the context. Here, the keypad had been carefully chosen... Have fun. You don't need to solve the whole input, just as many cases as you can. Not all, it could be impossible. You will get one point per case. For your information, my 1.2kB-python3 code got 4500 points, whereas my old 2kB-C one got 160000 points. (Edited 2017-02-11, after compiler changes). The Safe and its Lock Since 1984, there's too many terrorists, so Leo have a very secured safe with a very long password. He uses it to store all other passwords he needs. The only restriction of the password for that safe is that every pair of neighboring keys in the password is adjacent on the keypad. Adjacent means that the keys share a common edge. The secure door have a 6×6 lock which resembled this : A B C D E F G H I J K L M N O P Q R [Enter] S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0 [Enter] is not part of the password. Now, given the length of the password, we just would like to know how many different possibilities are there for the password. Input The input consists of 666666 lines. In each the 666666 lines there are two integers N, M. Output For as many test cases you can, on a single line, print the number of different passwords of length N. As the answer could be an enormous number, output the answer modulo M. Example Input: 1 10 2 100 987654321123456789 1000000000 [...] Output: 6 20 831617808 Explanations For a one key password, there are 36 possibilities, answer modulo 10 is 6 . For a two keys password, there are 120 possibilities, answer modulo 100 is 20 . For the last case, the answer has around 5×10¹⁷ digits, the nine last ones are 831617808 . Constraints 1 <= N <= 10^18 2 <= M <= 10^9 There's one input file, and data are uniform-randomly chosen in their range. Score As in the example, if you can output the 3 first correct answers, your score will be 3 points. No need to solve all the input, the minimum is 1 ; every solver in 'any' language will be able to check his SPPconstant-speed. Edit(12/II/2017) Now the MasterJudge takes time into account if you reach the limit of input file.
34,728
Fractionated morse cipher (FMORSE1) Fractionated morse is a classic cipher: The plaintext letters are in [A-Z] only with no punctuation. Each letter of the plaintext is first enciphered using Morse code with "|" after every letter. If the length of the resulting string is not multiple of three, you have to truncate the remaining symbols. Standard morse table: A=.-  B=-...  C=-.-.  D=-..  E=.  F=..-.  G=--.  H=....  I=..  J=.---  K=-.-  L=.-..  M=-- N=-.  O=---  P=.--.  Q=--.-  R=.-.  S=...  T=-  U=..-  V=...-  W=.--  X=-..-  Y=-.--  Z=--.. This series of [A-Z] and | letters is taken off in units of three, each trigraph set and cipher letters assigned to each group using a keyword alphabet to obtain the ciphertext. Fractionated morse table with keyword alphabet (key=ROUNDTABLE): R=...  O=..-  U=..|  N=.-.  D=.--  T=.-|  A=.|.  B=.|-  L=.||  E=-..  C=-.-  F=-.|  G=--. H=---  I=--|  J=-|.  K=-|-  M=-||  P=|..  Q=|.-  S=|.|  V=|-.  W=|--  X=|-|  Y=||.  Z=||- Your task is simple. You only will have to code the input message using the keyword. You have to reduce the keyword by the alphabet: (JIMMORRISON => JIMORSN reduced key) Score is the source length. Input N testcases (no more than 100) Each line of the input contains the keyword and a plaintext. The keylength max is 100 and the length of the plaintext is limited to 200. The last testcase ends with EOF. Output Output consist of exactly N lines of cyphertexts with letters in [A-Z] with no spaces. Example Input: JIMMORRISON RIDERSONTHESTORMINTOTHISHOUSEWEAREBORN Output: OQVNTNMGVXJNQAWKEHMELHKJQQNJWKSJURUSOUCAHOV
34,729
Matrix Exponentiation (MATEX) Many problems can be solved with matrix exponentiation. This task can be 'easily' solved with a O(log(N)) algorithm. You'll have to work on the constant to get more points. We'll work with a 'small' matrix and constant modulo. This task should help you to try some speed improvements for problems like R Numbers , Grid Tiling , and the great Flibonakki ... You don't need to solve the whole input, just as many cases as you can. Not all, it could be impossible. You will get one point per case. There will be one input file and the matrix will have a size W = 18 , unlike in the sample. For your information, my fastest 3kB-C code got 654321 points, with 31MB of memory usage. (Lot of stuff!) (Timing edited 2017-02-11, after compiler changes) Input The first line contains an integer number W : the size of the squared matrix. The W next lines contains W integers Mij : the coefficients of the matrix, line by line. In each the 838383 next lines there are three integers I, J, N. You don't have to read the whole input, just as many as you can solve... Output For as many test cases you can, on a single line, print the coefficient on the Ith line, Jth column of the matrix M^N (M to the power N). As the answer could be a big number, output the answer modulo 1000000007. Example Input: 5 32 82 7 66 30 57 1 28 2 89 53 66 6 35 61 45 87 88 24 20 35 22 23 80 93 1 1 1 1 5 2 5 1 3 5 5 99 [...] Output: 32 12795 2714937 764817976 Explanations For the first case: M^1 = 32 82 7 66 30 57 1 28 2 89 53 66 6 35 61 45 87 88 24 20 35 22 23 80 93 For the second case: M^2= 10089 9570 9060 6505 12795 6570 8655 2818 11912 11824 9486 9195 6738 9560 14203 12843 12113 5851 8400 16801 10448 13416 10178 12519 14660 For the third case: M^3= 2089068 2282253 1259668 2181834 3027095 1802809 2029855 1625446 1781368 2477165 2112086 2375941 1532239 2245976 3026032 2377555 2551827 1589794 2622329 3550751 2714937 2953573 1948704 2545886 3742082 Constraints W = 18 1 ≤ I,J ≤ W 1 ≤ Mij ≤ 10^9 1 ≤ N ≤ 10^18 Uniform-random input in the range. Score As in the example, if you can output the 4 first correct answers, your score will be 4 points. No need to solve all the input, the minimum is 1 ; every solver in 'any' language will be able to check his MATrix-EXponentiation-speed. Edit(12/II/2017) Now the MasterJudge takes time into account if you reach the limit of input file.
34,730
Quadratic primes (GOV04) Euler published the remarkable quadratic formula: n² + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41. Using computers, the incredible formula  n²  79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, 79 and 1601, is 126479. Considering quadratics of the form: n² + an + b, where |a|  1000 and |b|  1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. Euler published the remarkable quadratic formula: n² + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 40 2 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41. Using computers, the incredible formula  n² - 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The absolute product of the coefficients, 79 and 1601, is 126479. We are interested in producing better quadratic formulas.( which produces more prime numbers ) Considering quadratics of the form: n² + an + b, where |a| <= R and |b| <= R ( Your input will be the value of R ) where |n| is the modulus/absolute value of n e.g. |11| = 11 and | - 4| = 4 Find  a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. If two different values of n produces same prime, then we consider those primes as different (i.e. we count them twice) -- look at example. Remember |a| <= R and |b| <= R If you get multiple answers, choose the one having smallest value of a. Even then, if you get multiple answers, choose the equation having smallest value of b. Input First line of input contains an integer 't' representing the number of test cases. Then 't' lines follows. Each line contains an integer R. t<=8000 R<=10000 Output Output should be of the format: Integer 1<space>@<space>Integer2 Integer 1: Number of primes equation n 2 +an+b produces for consecutive value of n, starting from n=0. Integer 2: absolute product of the coefficients, a and b. Output of each test case should be on separate line.   Scoring Lesser your fingers work, better it is. :-) (Minimize your source code length) Example Input: 2 41 5 Output: 41 @ 41 5 @ 5 Explanation: case 1: a=-1 b=41 case 2: a=-1 b=5 ( Here n=0 and n=1 produces same prime 5, but we will count it twice)
34,731
Discrete Math Problem (shorten) (GCD4) Warning: This problem looks like, but differs from GCD3 : GCD3 : (2 K -2) ---vs--- GCD4 : (2 K -2) Moreover, your challenge will be to shorten your code to get more points. GCD4 could be harder than GCD3! Input The first line of input contains an integer T , the number of test cases. On each of the next T lines, your are given three integers N , M and K such that: N = a + b M = a 2 + b 2 - (2 K -2)×a×b with a > 0, b > 0 and gcd( a , b ) = 1 . Output For each test case, you have to print gcd( N , M ) , the greatest common divisor. Example Input: 2 2214811 1451126169481 7 107603 9066347749 9 Output: 1 1 Note: For the first trio a = 117651 and b = 2097160. For the second a = 1313 and b = 106290. Constraints 0 < T < 14321 0 < N < 10^200 1 < M < 10^200 0 < K < 17 For your information, my 293B C code get AC in 0.03s with 1.6MB of memory print. Size code limit will be 666B. Language restrictions are quite the same than in GCD3, and it is justified ;-) Have fun ;-)
34,732
Automatic Brainf##k Code Generator (Shortening AI) (BFK_AUTO) In this problem, you'll make an automatic Brainf**k code generator. Given a text file (input data), your program should output brainf**k code that if executed it will print the text file (exactly same with given input data). The text file containts printable ASCII character only: { '<line feed>'(ASCII(10)) , '<space>'(ASCII(32)) , ... , '~'(ASCII(126)) }. It's guaranteed that the filesize of text file is less than 1MB. Input Text file containing printable ASCII only with size<1MB. Output Brainf**k code that print that text file. Score Your score is: Sum of all BF code length in all test data Example Input: Hello World! Output: ++++++++++[>+++++++>++++++++++>+++>+<<<<-] >++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. Your Score (BF Code Length, valid command only): 111   Note: This is the first time I make my own judge, I've tested it hundred times with various test data, and so far no bug is found (found some but has been fixed). If you found a bug, you can send me info via PM or email, I'll fix that as soon as possible. Btw, here is the judge for this problem , maybe it'll be useful information for you. Good Luck and Have Fun :-D See also: Another problem added by Tjandra Satria Gunawan
34,733
Optimal Swap Sort (SWAPSORT) One day, Budi is learning selection sort , He like this sort because the swap operation is always less than n  where n  is number of element to be sorted. Budi is smart person, so he modify the algorithm and make number of swap is as small as possible (Optimal). Now He want your help to analyze his algo, He wonder what is the worst number of swap operation needed when His algo sort n  element(s) with k  different element(s). Input The first line there is an integer T  denoting number of test case. Next T  lines there are two integers n  and k for each line, n and k  has been described above. Output For each test case, output an integer that is the desired answer that has been described above. Constraints 1 ≤ T  ≤ 10 5 1 ≤ k  ≤ 10 9 k ≤ n ≤ 10 9 Example Input: 3 1 1 2 1 2 2 Output: 0 0 1 Explanation For first and second test case it has one different element so it already sorted, no need to do any swap operation. For last (third) test case if the element is decreasing (this is the worst case), only one swap is needed, then the sort is complete. Other Info Score is your source length. Seems that it's impossible to solve this problem using some programming languages e.g(Brainf**k, Intercal, etc). Click here to see my score for this problem (Link has been updated after rejudge) See also: Another problem added by Tjandra Satria Gunawan
34,734
Alice and Bob plays again (CDGOLF1) Alice and Bob are (again) playing a game. This time they are playing with Binary arrays.  A binary array is an array of integers whose elements can be either 0 or 1 .  At the start of the game, each player would be given one identical binary array. According to the game rules a player is allowed to perform exactly one type of operation. In each operation, (s)he can choose any element of his/her array and replace it with either 0 or 1 . A player can perform this operation any number of times.   The goal of the Alice is to obtain a representation where every 0 ’s will be further to the right than any of the 1 ’s; whereas the goal of Bob is to get every 1 ’s further to the right than any of the 0 ’s. The one who achieve this with minimum number of moves wins.   Your task is to determine the winner along with the number of toggle operations he/she performed. Input The first line of the input is an integer t (1 <= t <= 1024) , then t test cases follows. Each test case begins with an integer n (0 <= n <= 512) , denoting the length of the binary array. The next line contain the binary array of length n. Output The winner name followed by the minimum number of operations he/she performed to win the game. In case of a draw just output "Draw" (Quotes for clarity). Example Input: 3 5 11100 7 0001111 9 011010010 Output: Alice 0 Bob 0 Alice 3
34,735
Divisors (TJUC1) We define the function f( x ) = the number of divisors of x . Given two integers a and b ( a ≤ b ), please calculate f(a) + f(a+1) + ... + f(b).   Input Two integers a and b for each test case, 1 ≤ a ≤ b ≤ 2 31 - 1. The input is terminated by a line with a = b = 0. Output The value of f(a) + f(a+1) + ... + f(b). Sample Input 9 12 1 2147483647 0 0 Sample Output 15 46475828386   Hint For the first test case: 9 has 3 divisors: 1, 3, 9. 10 has 4 divisors: 1, 2, 5, 10. 11 has 2 divisors: 1, 11. 12 has 6 divisors: 1, 2, 3, 4, 6, 12. So the answer is 3 + 4 + 2 + 6 = 15.   if you find Source code limit is small here you can solve the tutorial version here : http://www.spoj.com/problems/TJUT1/
34,736
Guess The Number With Lies v1 (GUESSN1) GUESSN1 Judge has chosen an integer x in the range [1, n]. Your task is to find x, using query as described below. But be careful, because the Judge can lie. Judge is allowed to lie only once in single game and only in reply for query. Query Single query should contains set S = {a 1 , a 2 , ..., a k }. The reply for query is "YES", if x is in S. Otherwise the reply is "NO". 1 ≤ k < n 1 ≤ a 1  < a 2  < ... < a k  ≤ n Communication You should communicate with Judge using standard input and output. Attention: the program should clear the output buffer after printing each line. It can be done using fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution - setlinebuf(stdout). The first line of input contains single integer T, the number of games. Then T games follow. At the beggining of each game You should send to the Judge a line with command "START_GAME". The Judge will answer You with numbers n, m, where n is as described above and m is the maximum number of queries that You can use in this game. Then You should send some queries, every query is a line with "QUERY" keyword, then single-space separated values k a 1 a 2 ... a k . After each query the Judge will answer "YES" or "NO". At the end of game You should give answer: "ANSWER y", where 1 ≤ y ≤ n is the answer for the game. When y ≠ x, the solution will got WA. Then start the next game (if there is any). Scoring Total score is the sum of scores of single games. If You use c queries in game, Your score is c 2 . The smaller score is the better score. Constraints 1 ≤ T ≤ 2 7 2 ≤ n ≤ 2 17 Example The example of communication. J=Judge, P=Player. J: 3 P: START_GAME J: 2 10 P: QUERY 1 1 J: YES P: QUERY 1 2 J: YES P: QUERY 1 1 J: NO P: ANSWER 2 P: START_GAME J: 2 10 P: QUERY 1 1 J: YES P: QUERY 1 2 J: NO P: ANSWER 1 P: START_GAME J: 5 25 P: QUERY 3 1 3 5 J: YES P: QUERY 2 2 4 J: YES P: QUERY 3 1 2 3 J: YES P: QUERY 2 1 2 J: NO P: ANSWER 3 Explanation: In 1st game there is conflicting information in first and second query, so we know, that the last query isn't lie. In 2nd game the Judge don't use lie (Judge can lie once, but don't need to do it). In 3rd game there is conflicting information in first and second query, so the next queries has correct answers. The score is 3 2 + 2 2 + 4 2 = 9 + 4 + 16 = 29 Note Be careful. The Judge will try to maximize the number of queries that You will ask. If necessary, the Jugde can also replace chosen value x with the other one. But don't worry too much - at the end of the game, the value x chosen by Judge will satisfy all except at most one of Your queries. Note 2 If You got SIGXFSZ error, You probably use unnecessary numbers in queries. Let's see at the example: P: START_GAME J: 16 9 P: QUERY 2 1 2 J: NO P: QUERY 3 1 2 3 J: NO P: QUERY 4 1 2 3 4 J: NO P: QUERY 5 1 2 3 4 5 J: NO P: QUERY 6 1 2 3 4 5 6 J: NO In 3rd query, there are unnecessary numbers 1 and 2. This numbers cannot be the answer for this game, because the Judge said twice (in 1st and 2nd query's reply) "1 and 2 are not OK!", but the Judge can lie only once. From the same reason in 4th query, the unnecessary numbers are 1, 2 and 3. In 5th query, unnecessary number are 1, 2, 3 and 4. When n is big enough, the profit from this optimization is huge (and probably SIGXFSZ won't appear). Similar problems There is a family of similar problems. Here is the table with them: Code Number of lies Query format Type Section Difficulty GUESSN1 1 subset interactive challenge easy GUESSN2 2-16 subset interactive challenge medium/hard GUESSN3 1 range interactive classical medium GUESSN4 1 subset non-interactive challenge medium GUESSN5 2-16 subset non-interactive challenge hard subset - the query is about any subset of {1,2,...,n} range - the query is about any range [a,b]  interactive - the Judge replies after every query non-interactive - all queries have to be asked at once, before any reply
34,737
Guess The Number With Lies v2 (GUESSN2) GUESSN2 Judge has chosen an integer x in the range [1, n]. Your task is to find x, using query as described below. But be careful, because the Judge is a liar. Judge is allowed to lie up to w times in single game and only in reply for query. Query Single query should contains set S = {a 1 , a 2 , ..., a k }. The reply for query is "YES", if x is in S. Otherwise the reply is "NO". 1 ≤ k < n 1 ≤ a 1  < a 2  < ... < a k  ≤ n Communication You should communicate with Judge using standard input and output. Attention: the program should clear the output buffer after printing each line. It can be done using fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution - setlinebuf(stdout). The first line of input contains single integer T, the number of games. Then T games follow. At the beggining of each game You should send to the Judge a line with command "START_GAME". The Judge will answer You with numbers n, w, m, where n, w are as described above and m is the maximum number of queries that You can use in this game. Then You should send some queries, every query is a line with "QUERY" keyword, then single-space separated values k a 1 a 2 ... a k . After each query the Judge will answer "YES" or "NO". At the end of game You should give answer: "ANSWER y", where 0 ≤ y ≤ n; y=0 means, that You skip this game without the correct answer. Otherwise y is the answer for the game. When y ≠ x, the solution will got WA. Then start the next game (if there is any). Scoring Total score is the sum of scores of single games. If You use c queries in game and You find the x value, Your score is c 2 . If You skip the game, the score is 4m 2 . The smaller score is the better score. Constraints 1 ≤ T ≤ 2 7 2 ≤ n ≤ 2 17 2 ≤ w ≤ 2 4 1 ≤ w * n ≤ 2 19 Example The example of communication. J=Judge, P=Player. J: 3 P: START_GAME J: 2 2 10 P: QUERY 1 1 J: YES P: QUERY 1 1 J: YES P: QUERY 1 1 J: YES P: ANSWER 1 P: START_GAME J: 2 4 10 P: QUERY 1 2 J: YES P: QUERY 1 2 J: YES P: QUERY 1 1 J: YES P: QUERY 1 1 J: YES P: QUERY 1 2 J: YES P: QUERY 1 2 J: YES P: QUERY 1 2 J: NO P: QUERY 1 1 J: NO P: ANSWER 2 P: START_GAME J: 12345 7 100 P: ANSWER 0 Explanation: In 1st game Judge said 3 times, that his number is 1 and he didn't lie. The answer is 1, because he can lie only 2 times. In 2nd game the Judge lied in 3rd, 4th and 7th query. In 3rd game the Player gave up. The score is 4 * 100 2 . The score is 3 2 + 8 2  + 4*100 2 = 9 + 64 + 40000= 40073 Note Be careful. The Judge will try to maximize the number of queries that You will ask. If necessary, the Jugde can also replace chosen value x with the other one. But don't worry too much - at the end of the game, the value x chosen by Judge will satisfy all except at most w of Your queries. Note 2 If You got SIGXFSZ error, You probably use unnecessary numbers in queries. Let's see at the example: P: START_GAME J: 16 2 14 P: QUERY 2 1 2 J: NO P: QUERY 3 1 2 3 J: NO P: QUERY 4 1 2 3 4 J: NO P: QUERY 5 1 2 3 4 5 J: NO P: QUERY 6 1 2 3 4 5 6 J: NO In 4th query, there are unnecessary numbers 1 and 2. This numbers cannot be the answer for this game, because the Judge said three times (in 1st, 2nd and 3rd query's reply) "1 and 2 are not OK!", but the Jugde can lie only 2 times. From the same reason in 5th query, the unnecessary numbers are 1, 2 and 3. When n is big enough, the profit from this optimization is huge (and probably SIGXFSZ won't appear). Similar problems There is a family of similar problems. Here is the table with them: Code Number of lies Query format Type Section Difficulty GUESSN1 1 subset interactive challenge easy GUESSN2 2-16 subset interactive challenge medium/hard GUESSN3 1 range interactive classical medium GUESSN4 1 subset non-interactive challenge medium GUESSN5 2-16 subset non-interactive challenge hard subset - the query is about any subset of {1,2,...,n} range - the query is about any range [a,b]  interactive - the Judge replies after every query non-interactive - all queries have to be asked at once, before any reply
34,738
Guess The Number With Lies v4 (GUESSN4) GUESSN4 Judge has chosen an integer x in the range [1, n]. Your task is to find x, using at most m queries as described below. But be careful, because there are 2 important things: 1. The Judge can lie. Judge is allowed to lie only once in single game and only in reply for query. 2. You must prepare all queries at once and send all of them to the Judge before You got any reply. Query Single query should contains string s 1 s 2 s 3 ...s n , where s i is '0' or '1'. The reply for query is "YES", if s x = '1', or "NO" otherwise. For example, when n=8, x=5 and query is "00101011", the Judge will reply "YES" (if telling the truth) or "NO" (if lying), because the 5th character in query is '1'. Real task and scoring The real task is not to find the number x chosen by Judge, but only to prepare queries, which allow You to guess the x value for every possible Judge's reply. The Judge won't give You reply for Your queries. If the Judge will find such reply for Your queries, that there will be more than one x value possible, You will fail the test case (see example for detail explanation). Otherwise You succeed. If You succeed, Your score is q 2 , where q is the number of queries, that You use. If You fail, You got penalty score equal to 4m 2 . Total score is the sum of scores of single games. The smaller score is the better score. Input The first line of input contains one integer T - the number of test cases. Then T test cases follow. Each test case contains one line with two single-space separated integers n and m, where n is the size of the game and m is the maximal number of queries, that You can use. Output For each test case print a line with one integer q - the number of queries that You want to ask. Then print q lines with Your queries. Each query should be string of length n, with all characters '0' or '1'. Constraints 1 ≤ T ≤ 2 7 2 ≤ n ≤ 2 16 3 ⌈log 2 n⌉ ≤ m 0 ≤ q ≤ m For bigger tests, number of test cases is smaller (T ≤ 40 for 10000 ≤ m ≤ 20000, T ≤ 20 for 20000 ≤ n ≤ 30000, T ≤ 10 for 30000 ≤ n) Example Input: 5 2 4 3 9 32 32 4 10 5 12 One of possible output is: 4 01 01 10 10 9 001 001 001 010 010 010 100 100 100 0 2 0011 0110 6 00011 00101 00110 01110 01101 01011 Explanation: Notation: reply "YYN..." means, that Judge replied "YES" for first and second query, "NO" for third query, and so on... In 1st test case there are only two numbers. Judge can reply "YYNN", "NNYY" (without lie) or "YNNN", "NYNN", "YYNY", "YYYN", "NYYY", "YNYY", "NNNY", "NNYN" (with one lie). The other replies ("YYYY", "NNNN", "YNYN", "YNNY", "NYNY", "NYYN") are not ok, because for every of them and for every possible x value, the Judge lies more than once. For each good reply, there is only one integer from range [1, 2], that match this replies ("match" means match all except at most one of queries). The score is 4 2 = 16. Notice, that You can use the same query more than once. In 2nd test case player asked three times for every single integer. Because Judge can lie only once, the player is able to detect the lie, and choose the value x correctly. The score is 9 2 = 81. In 3rd test case player decided to skip. Player got the penalty score 4 * 32 2 = 4096. In 4th test case player tried to give the solution, but the solution is wrong. There is impossible to guess the x value in only two queries. The Judge can reply for example "YY" and then x can be 2, 3 or 4. The score is penalty score 4 * 10 2 = 400. In 5th test case the nubmer of queries given by player is smaller than the maximal possible number. For every possible Judge's reply there is only one possible value of x, so test succeeded. The score is 6 2 = 36. Total score is 16 + 81 + 4096 + 400 + 36 = 4629. Similar problems There is a family of similar problems. Here is the table with them: Code Number of lies Query format Type Section Difficulty GUESSN1 1 subset interactive challenge easy GUESSN2 2-16 subset interactive challenge medium/hard GUESSN3 1 range interactive classical medium GUESSN4 1 subset non-interactive challenge medium GUESSN5 2-16 subset non-interactive challenge hard subset - the query is about any subset of {1,2,...,n} range - the query is about any range [a,b]  interactive - the Judge replies after every query non-interactive - all queries have to be asked at once, before any reply
34,739
Guess The Number With Lies v5 (GUESSN5) GUESSN5 Judge has chosen an integer x in the range [1, n]. Your task is to find x, using at most m queries as described below. But be careful, because there are 2 important things: 1. The Judge can lie. Judge is allowed to lie w times in single game and only in reply for query. 2. You must prepare all queries at once and send all of them to the Judge before You got any reply. Query Single query should contains string s 1 s 2 s 3 ...s n , where s i is '0' or '1'. The reply for query is "YES", if s x = '1', or "NO" otherwise. For example, when n=8, x=5 and query is "00101011", the Judge will reply "YES" (if telling the truth) or "NO" (if lying), because the 5th character in query is '1'. Real task and scoring The real task is not to find the number x chosen by Judge, but only to prepare queries, which allow You to guess the x value for every possible Judge's reply. The Judge won't give You reply for Your queries. If the Judge will find such reply for Your queries, that there will be more than one x value possible, You will fail the test case (see example for detail explanation). Otherwise You succeed. If You succeed, Your score is q 2 , where q is the number of queries, that You use. If You fail, You got penalty score equal to 4m 2 . Total score is the sum of scores of single games. The smaller score is the better score. Input The first line of input contains one integer T - the number of test cases. Then T test cases follow. Each test case contains one line with three single-space separated integers n, w and m, where n is the size of the game, w is the maximal number of lies and m is the maximal number of queries, that You can use. Output For each test case print a line with one integer q - the number of queries that You want to ask. Then print q lines with Your queries. Each query should be string of length n, with all characters '0' or '1'. Constraints 1 ≤ T ≤ 2 7 2 ≤ w ≤ 2 4 2 ≤ n ≤ 2 12 (2w+1) * ⌈log 2 n⌉ ≤ m 0 ≤ q ≤ m Example Input: 4 2 2 6 2 3 8 2 16 34 5 2 18 One of possible output is: 6 01 01 01 01 01 01 6 01 01 01 01 01 01 0 15 00011 00011 00011 00011 00011 01010 01010 01010 01010 01010 00100 00101 00110 01100 01111 Explanation: Notation: reply "YYN..." means, that Judge replied "YES" for first and second query, "NO" for third query, and so on... In 1st test case there are only two numbers. Judge can reply "YYYYYY", "NNNNNN" (without lie), "YYYYYN", "YYYYNY", "YYYNYY", "YYNYYY", "YNYYYY", "NYYYYY", "NNNNNY", "NNNNYN", "NNNYNN", "NNYNNN", "NYNNNN", "YNNNNN", (with one lie) or "NNNNYY", "NNNYNY", "NNNYYN", "NNYNNY", "NNYNYN", "NNYYNN", "NYNNNY", "NYNNYN", "NYNYNN", "NYYNNN", "YNNNNY", "YNNNYN", "YNNYNN", "YNYNNN", "YYNNNN", "NNYYYY", "NYNYYY", "NYYNYY", "NYYYNY", "NYYYYN", "YNNYYY", "YNYNYY", "YNYYNY", "YNYYYN", "YYNNYY", "YYNYNY", "YYNYYN", "YYYNNY", "YYYNYN", "YYYYNN" (with 2 lies). The other replies ("NNNYYY", "NNYNYY", "NNYYNY", "NNYYYN", "NYNNYY", "NYNYNY", "NYNYYN", "NYYNNY", "NYYNYN", "NYYYNN", "YNNNYY", "YNNYNY", "YNNYYN", "YNYNNY", "YNYNYN", "YNYYNN", "YYNNNY", "YYNNYN", "YYNYNN", "YYYNNN") are not ok, because for every of them and for every possible x value, the Judge lies more than two times. For each good reply, there is only one integer from range [1, 2], that match this replies ("match" means match all except at most two of queries). The score is 6 2 = 36. Notice, that You can use the same query more than once. In 2nd test case player tried to give the solution, but the solution is wrong. The Judge can reply for example "YYYNNN" and then for both possible values of x the judge lied 3 times. Player needs more queries in this case. The score is penalty score 4 * 8 2 = 256. In 3rd test case player decided to skip. Player got the penalty score 4 * 34 2 = 4624. In 4th test case the nubmer of queries given by player is smaller than the maximal possible number. For every possible Judge's reply there is only one possible value of x, so test succeeded. The score is 15 2 = 225. Total score is 36 + 256 + 4624 + 225 = 5141. Similar problems There is a family of similar problems. Here is the table with them: Code Number of lies Query format Type Section Difficulty GUESSN1 1 subset interactive challenge easy GUESSN2 2-16 subset interactive challenge medium/hard GUESSN3 1 range interactive classical medium GUESSN4 1 subset non-interactive challenge medium GUESSN5 2-16 subset non-interactive challenge hard subset - the query is about any subset of {1,2,...,n} range - the query is about any range [a,b]  interactive - the Judge replies after every query non-interactive - all queries have to be asked at once, before any reply
34,740
Tone Transposition (TONES) Nalin really loves music, just like her father. When she was a child, she got keyboard classes at a private school. After she got married, she decided to play and sing a music for her husband at the piano. She searched for the song Endless Love over the internet to learn how to play it, but, unfortunately, the tone wasn't good enough for her to sing. If it was a keyboard, she could just hit a button and the problem would be solved, but there's no such button in a piano. She began to make the tone transposition with a paper and a pen, but it was taking too long, then she asked her husband to write her a program to do it, without telling him what was it for. If you want to know a little bit more about tone transposition, in order to solve the problem, please read the end of problem statement. Input In each test cases, first line is n<=1000 and in the next line, a number t, -12<=t<=+12. In the third, and last, line of each case, n chords follow. All chords, whose size does not exceed 15 characters, are valid chords from music theory such as CMajor, F#Major, D#Maj7, A#b5, G7(b5)(b9), etc., and they are composed of letters, numbers and the following symbols "(", ")", "#", "-". There's no flat for chords in the input (Bb for example is represented as A#) and also there's no bass inversion, such as G4/B. The end of input is when n=0. Output The sequence of n chords transposed by t semitones, one per line. Score Source length. Input: 7 -3 C D E F G A B 8 +2 C Am Dm G C Am Dm G 4 +4 F#m D A E 5 +2 Gmaj7 D D#dim7 Em7 C9 0 Output: A B C# D E F# G# D Bm Em A D Bm Em A A#m F# C# G# Amaj7 E Fdim7 F#m7 D9 The sequences of chords is: C C# D D# E F F# G G# A A# B. Perform a tone transposition by t semitones is just shifting a note through the list above. For example: if you have C and want to transpose it by +2, it goes to D. If it has a suffix, you just keep the suffix like: Cm7 by +2 goes to Dm7. If you transpose B by +1, it goes to C. If t is negative, you just have to go backwards.
34,741
Colour Brick Game (BRICKGM) BRICKGM Let's consider the tetris like game. The rules are very easy, there is board of width 10 and height 20. Colour bricks fall down the board. Every brick contains 3 colours. Player can rotate colours in the brick and determine the column, in which to place current brick. The goal is to construct horizontal, vertical or diagonal lines of length 3 or more in the same colour. After every brick falls down, the cleaning up algorithm is executed. Single step of cleaning up algorithm searchs for lines constructed from cells with the same colour (there can be more than one such line). If no line is found, the algorithm finishes. Otherwise all cells in all found lines disappear, then the cells above this dissapeared cells fall down. The cleaning up algorithm executes single steps as long, as there are any changes on the board. The brick can be rotated. When the brick contains colours A, B, C (from top to bottom), then single rotation makes the brick with colours C, A, B, and double rotation makes the brick with colours B, C, A.     Task Your task is to write the program, which can play in Colour Brick Game. You will receive the consecutive bricks and for each of them have to determine the correct column and rotation. For each cleaned line You got points (according to scoring section). The goal is to maximize the score. Input The first line of input contains single-space separated integers n and k (3 ≤ k ≤ 9, 1 ≤ n*k ≤ 10 6 ), where n is the number of bricks in the game and k is the number of different colours, that can appear in the game. The next n lines contain bricks description, one line per brick. Each brick is represented as string of length 3, containing digits (every digit is from 1 to k). Output For every brick from the input, You should write a line with two single-space separated integers x and r (1 ≤ x ≤ 10, 0 ≤ r ≤ 2), where x is the number of column to place the brick and r is the rotation of the brick (0 for no rotation, 1 for single rotation, 2 for double rotation). If after falling down the brick is located outside the board (the higher brick cell is higher than the highest board row), the game finishes immediately. The judge doesn't read the remaining moves, so You don't need to output them. You can also stop, when there is no valid move at the board and You don't need to output this last move. Scoring Base score for cleaned line of length m is m 2 . The base score is multiplied by the number of lines cleaned in single cleaning up step and then multiplied by the cleaning up step number (see example for clarify). The brick score is sum of scores received from cleaned lines after the brick falled down. Total score is sum of brick scores. Example Input 1: Output 1: 11 5 211 321 232 233 345 245 451 332 451 332 312 1 1 2 0 3 0 3 2 4 0 5 0 6 0 6 0 7 0 7 0 8 1   Input 2: Output 2: 11 5 211 321 232 233 345 245 451 332 451 332 312 1 0 1 0 1 0 1 0 1 0 1 0 1 0 Explanation In first example, for the first 10 bricks there is no line to clean. The last brick makes lines to clean in 4 cleaning up steps. In 1st step there is only one line of length 3 to clean. The score is 3 2, multiplied by 1 (number of lines cleared in the step) and multiplied by 1 (number of step). 3 2 *1*1 = 9. In 2nd step there are 3 lines (one of length 3, two of length 4). The score is 3 2 +4 2 +4 2 , multiplied by 3 (number of lines cleared), multiplied by 2 (number of step). (3 2 +4 2 +4 2 )*3*2 = 41*6 = 246. In 3rd step there are 2 lines (both of length 3). The score is (3 2 +3 2 )*2*3 = 18*6 = 108 In 4th step there are 2 lines of length 3. The score is (3 2 +3 2 )*2*4 = 18*8 = 144. Total score is 9 + 246 + 108 + 144 = 507.   In second example player placed all bricks in 1st column. There is no cleaned line, so the 7th brick after falling down is located outside the board. The game finishes with score 0. Note, that there is only 7 lines in output.
34,742
Boring Factorials (Ultimate) (BORING3) Factorial is one of the most attractive word this week, it is proposed to reload a famous problem . Is it so boring ? As the reload edition wasn't hard enough, we'll make a challenge edition with harder constraints. Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friend has been helping them out. But as it goes, Sameer and Arpit have got bored of problems involving factorials. Reason being, the factorials are too easy to calculate in problems as they only require the residue modulo some prime and that is easy to calculate in linear time. So to make things interesting for them, Aman - The Mathemagician, gives them an interesting task. He gives them a prime number P and an integer N (not so) close to P , and asks them to find N! modulo P . He asks T such queries. Input The input contains several lines. Probably, you'll can't process all ; please exit your program before the time limit. Warning : To allow more input, its presentation is different than in other BORING* problems. On each line, your are given two integers D (delta), and P a prime number. Output For as many test cases you can, you have to print (P-D)! modulo P . Example Input: warning , it's different from other BORING* input. 3 5 6 11 50 71 [...] Output: 2 10 6 [...] Constraints 0 <= D <= 10^6 1 < P < 10^100, a prime number For your information : With Python3, my "brute force" got 435 points, my first code for (BORING1/2) got 1631 points ; my new BORING3 code got 2772 (edit 4041) points to be challenged. ;-) Have fun. Edit(12/II/2017) Now the MasterJudge takes time into account if you reach the limit of input file : There's only 300000 lines.
34,743
The Secret Recipe (CEBITO) As the Carnival period draws to an end, the remote Kingdom of Byteland is making preparations for the donut feast of Mardi Gras . The King's Court is eagerly anticipating the arrival of notable guests and crowned heads from all round the continent, who will partake of the ceremonial strawberry donut dinner in the Royal Halls. But this year, just before the feast is due to commence, disaster has struck: The Recipe for strawberry donuts, jealously guarded by the Lord Master of the Household, has been destroyed in a kitchen fire caused by an overturned frying pan! Panic and dispair have spread through the King's Court. Without The Recipe, noone is able to fry a half-reasonable donut. The one hope of salvation is in an old, almost forgotten legend, which says that in a far-off part of Byteland, there lives a dynasty of Wicked Old Witches, who hold another copy of The Recipe, treasuring it and passing it on from mother to daughter. In a valiant effort to save the face of the Kingdom of Byteland, you set out on an expedition to find the Witches and their strawberry donut Recipe! After climbing many hills and crossing many seas, you eventually reach a small village in which all of the legendary Witches dwell. The good news is that one copy of the Recipe is still in existance, and is held by one of the living witches. To make things even better, it turns out that the Witches are not as Wicked as the legend states: in fact, they are quite sociable, and may even help you locate the witch who has the Recipe. However, each witch will insist on telling you her life story first, before you can get any useful information out of her. And they are all Old Witches, so it may take a while, and you really don't want to interrupt a Witch when she is talking. Only after a Witch has recounted her countless tales, will she tell you what she knows about the recipe, which will be something along the following lines: "The recipe? Oh dear, I'm sorry, I've never seen it myself..."  "The recipe? Yes, I do remember... I had it once, many years ago, but I have since passed it on to my most talented daughter (and here comes the name of the daughter in question). Her cooking is so much better than mine, you know!" "The recipe? But why of course! Here it is. Just make sure you keep it safe!" (This is the answer you want to hear, but you will only hear it from the one Witch who has the recipe.) Mardi Gras is drawing near, and you may sadly not have enough time to talk to all the charming Old Witches. Try to figure out a way to obtain the recipe, and to do it as quickly as possible!  Input The input starts with a single positive integer integer k , denoting the number of Witches in the dynasty ( k < 10 6 ). The next line starts with the name of the oldest Witch, from whom all the other Witches are descended, and who of course must have once held the recipe, even if she may perhaps not have it now. The input line describing this Witch is of the form: Name chats x  min. Each of the next k -1 lines contains a description of a Witch, formatted as follows: Name is the daughter of Mother's-Name and chats x  min. The number x  describes the number of minutes of your time a Witch will take up if you talk to her: an integer between 1 and 10 6 . All names of witches are sequences of exactly 5 letters, starting with one upper-case letter (A-Z) and followed by 4 lower-case letters (a-z). The order of Witches at input is such that each Witch is described later than her mother. No two Witches in the dynasty share the same name. Output Your output should describe the strategy you adopt when talking to the witches, with a complete plan of action, stating who to approach in what order, depending on previously obtained answers. First, print the name of the witch you approach as the first, followed by a list of clauses of the form ANSWER  ->  FURTHER_ACTION , one clause corresponding to each of the possible answers which may be given by the Witch. For every Witch, you should consider all possible answers the witch may give you, which are feasible given the information you have obtained so far from other Witches. For compactness, assume that in the case when a Witch directs you to her daughter, the ANSWER string is simply to be the name of the daughter in question. If the Witch answers that she has no idea of the recipe, the ANSWER string should be: NEVER . If a Witch tells you she has the recipe, no further action needs to be taken, and you shoud not write any text corresponding to such an answer in your output file. (In particular, if you can be sure that the Witch you have just asked has the recipe, you should not print text corresponding to any answers given by this Witch.) The  ANSWER  string should be followed by a description of FURTHER_ACTION to take, representing actions which you will subsequently take, subject to the given answer. The FURTHER_ACTION should be written down following the same grammar rules as those describing the whole of your program's output (i.e., this paragraph is to be read recursively).  White spaces (spaces, newlines, and tabs), numbers, and punctuation marks may be inserted arbitrarily into your program's output to improve its formatting; they will be disregarded when testing your solution. The order in which you consider the possible answers of each Witch is arbitrary.  In your strategy  you may never approach a Witch if, based on information received so far, you can be sure she does not have the recipe. You can assume that Witches always tell the truth, and should not print any text corresponding to the case of an answer which you already know may not occur. You can also safely assume that the recipe does not change hands while you are in the Witches' village. Scoring For each data set, the score of your program will be computed as the ratio of two integer values, t / T . Here, t  denotes the number of minutes required for a conversation with the most talkative Witch in the dynasty, and T  is the total amount of time your strategy takes to find the recipe for a worst-case scenario of answers. Your program will be tested for multiple data files. The overall score of your program will be the average of scores obtained for individual data sets. Notes The time limit of your program for each data set is 10 seconds. Your program must not print more than 30MB of output text (whitespace included!). The number of Witches k will be approximately  10 3 (for half of the tests) and approximately 10 5  (for the remaining tests). Example Input: 5 Alice chats 20 min. Betty is the daughter of Alice and chats 10 min. Chloe is the daughter of Alice and chats 10 min. Marie is the daughter of Chloe and chats 30 min. Suzie is the daughter of Marie and chats 10 min. Sample output 1: 1. Chloe: * "Marie!" 2. Suzie: * "NEVER!" 3. Marie. * "NEVER!" 2. Alice: * "Betty!" 3. Betty. Score: 0.6 Explanation: In the presented solution, you first approach Chloe and talk to her for 10 minutes. If Chloe tells you she gave the recipe to her only daughter, Marie, then you next approach Suzie and talk to her for 10 minutes. If she does not have the recipe, then it must be with Marie; you talk to her next for 30 minutes, and obtain the recipe (after at most 50 minutes in total). If Chloe tells you she has not seen the recipe, you next approach Alice. As the oldest witch, Alice must have seen the recipe, and if she doesn't have it, she must have given it to Betty. Talking to Alice takes up 20 minutes of your time, and talking to Betty takes up another 10 minutes. In this case, you will obtain the recipe after at most 40 minutes. The score of your program is the time required to talk to the most talkative witch in the dynasty, Marie, divided by the worst-case time needed to obtain the recipe in the provided solution, i.e., 30/50. Sample output 2: 1. Alice: * "Chloe!" 2. Chloe: * "Marie!" 3. Marie: * "Suzie!" 4. Suzie. * "Betty!" 2. Betty. Score: 0.429 Sample output 3: 1. Alice: * "Chloe!" 2. Betty: etc. Evaluation: Wrong Answer. Note that once you know the Recipe is in Chloe's part of the family, it cannot be with Betty. Sample output 4: 1. Alice: * "Chloe!" 2. Chloe: * "NEVER!" etc. Evaluation: Wrong Answer. Note that once you know the Recipe has passed through Chloe's hands, it must either be with her or with one of her daughters. Sample output 5: Chloe Marie Suzie NEVER Marie NEVER Alice Betty Betty Score 0.6 This solution is completely equivalent to Sample output 1.
34,744
Sum of primes (SUMPRIM1) Léo had been defeated by XerK at the battle of the ThermoPell. 300 braves fell ; XerK as a living God decided to allow a new honor table, for those who can use less than 900 characters in his new problem. This problem is extremely simple, but you have to be extremely fast. Input The lonely line of input contains an integer N . Output You have to print the sum of all primes up to N . Examples Input_1: 19 Output_1: 77 Input_2: 1000000000 Output_2: 24739512092254535 Explanation The first sum is 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 = 77 Constraints 0 < N <= 2×10^9 The classical problem SUMPRIM2 is the reverse task. Time limit allows some slow languages to finish in time, it could be hard. For your information, my 690-Byte C code need a total time of 0.76s for the 30 input files, 22.82s for my Python one. (Edit 12/II/2017, after compiler update). Warning : You have 900B as code size limit. ;-) Have fun.
34,745
Modular Bernoulli (MODBERN) Bernoulli numbers are of great interest in mathematics and in computational sciences. They are rationnal numbers, our interest will be the numerator of the reduced fraction. Ada Lovelace is sometimes credited as the first programmer ; her interest was on Bernoulli numbers. You have less than two years before the 200th birthday of Ada, here is a good place to improve your skills. Input The input contains several lines, you don't have to process all, it may be hard, only all first ones you are able to, in the given time. Each line contains two integers : N , and P a prime number. Output For each line you will process, print numerator (B N ) . As the answer could not fit in a 64-bit container, just output your answer modulo P , lying in [0...P[ . Example Input: 2 5 5 7 10 13 12 23 [...] some more lines Output: 1 0 5 22 [...] as many as you can. Explanation For the fourth case, B 12 = (-691)/2730 , and (-691) mod 23 = 22. Constraints 1 < N <= 10000 2 < P <= 30000, a prime number Input contains uniform distribution. The challenge is to be the fastest, constraints allow everybody to get some points. There are 100000 lines, one point per case. If you can process all 10^5 lines, your score is 10^6/time. Have fun ;-)
34,746
Power Sum (PWSUMC) Some people may found PWSUM a too easy problem. We propose here some serious constraints. Input The input contains several lines, you don't have to process all, it may be impossible, only all first ones you are able to, in the given time. Each line contains two integers : N , and P , a prime number. Output For the k th line, print Sum(i^k for i in [1..N]) . As the answer could not fit in a 64-bit container, just output your answer modulo P . The difficulty will seriously increase as you will process lines. Example Input: 2 5 3 7 2 13 [...] some more lines Output: 3 0 9 [...] as many as you can. Explanations For the first line : 1^1 + 2^1 = 3 (mod[5]). For the second line : 1^2 + 2^2 + 3^2 = 14 = 0 (mod[7]) For the third line : 1^3 + 2^3 = 9 (mod[13]). Constraints 0 < N <= 10^9 1 < P <= 10^9, a prime number The numbers N are uniform randomly chosen. The prime numbers P are log-uniform randomly chosen. The challenge is to be the fastest. There are 100000 lines, one point per case. Constraints allow everybody to get some points. Have fun ;-)
34,747
Fibonacci Power Sum (PWSUMF) Some people may found FIBOSUM a too easy problem. We propose here some serious constraints. Fib is the Fibonacci sequence: For any positive integer i: if i<2 Fib(i) = i, else Fib(i) = Fib(i-1) + Fib(i-2) Input The input contains several lines, you don't have to process all, it may be hard, only all first ones you are able to, in the given time. Each line contains one integer : N . Output For the k th line, print Sum(Fib( i )^ k for i in [1.. N ]) . As the answer could not fit in a 64-bit container, just output your answer modulo 1000000007. The difficulty should increase as you will process lines. Example Input: 6 6 6 [...] some more lines Output: 20 104 674 [...] as many as you can. Explanations For the first line : 1^1 + 1^1 + 2^1 + 3^1 + 5^1 + 8^1 = 20. For the second line : 1^2 + 1^2 + 2^2 + 3^2 + 5^2 + 8^2 = 104 For the third line : 1^3 + 1^3 + 2^3 + 3^3 + 5^3 + 8^3 = 674. Constraints 0 < N <= 10^9 The numbers N are uniform randomly chosen. The challenge is to be the fastest. There were 30000 lines at time of publication. Robert Gerbicz agreed to extend to 100000 lines using his fast C code. Congratulations again to him as a fabulous solver. Now you have one point for the k th line. Constraints allow everybody to get some points. If a much faster method is discovered, judge would take time into account. For your information, my (our) method have an amortized complexity of O(k) for the kth line. Have fun ;-)
34,748
PPrimes (PPRIME) N  is a  prime number  if it has no positive divisors other than  1  and  N . Prime numbers in sorted arrangement will a  prime sequence . First 10 primes of this sequence are  2,3,5,7,11,13,17,19  and  23  [Note:  1  is not prime] Here we can say that  2 is 1st prime  [Since it is at 1st location in the sequence] 3 is 2nd prime 5 is 3rd prime  and so on… A  PPrime  is a number which is at a prime position in the above  prime sequence . Eg.  2  is a  Prime  but not a  PPrime  because it is at position  1  in the prime sequence, which is not a prime position (as  1  is not prime). However  3  is a  PPrime  because it is at position  2 , which is a  prime position  (as  2  is prime). Your task is to simply print the first  10,000 PPrimes . The twist here is that you have to do so using the shortest possible code. Shorter the code, better the score. Input No Input Output Print first 10,000 PPrimes separated by a space Scoring Shortest code wins ;)
34,749
Strchr in BF (BFSTR1) Wonder if string functions are possible in brainf**k? Well, as Rivu says, "Impossible is nothing!!!".   Given a character (lower or upper case letter) and a character string, your task is to find the first occurance of the given character in this string and print its index. For a string of length N , the index numbering starts from 1 to N . Simple, Isn't it? Only 256 bytes allowed. Still simple? Well, try and minimize it. Input First line of the input contains T  , which comprises of 2 digits, representing the number of test cases. The next T  lines of the input contain a test case each. Each of these lines start with a character, say C,   followed by a space and then a string of characters, say STR . Each line of the input ends with a newline  character. Contraints: 0 < T < 10 0 < length of STR < 10 Output For every test case, output the  INDEX  of the first occurence of C in STR . If the character C  is NOT found in STR , output 0 . Example Input: 03 F BrianFuck c strcmp m mama   Output:   6 4 1   SCORE is your source length. NOTE: This question does NOT use exact judge. So, you can print any space character between the test cases.
34,750
Counting triangles 2 (CT2) Consider a 2D integer grid with lower left corner at (0, 0) and upper right corner at (X, Y) . We are interested in isosceles right triangles with all the 3 corners at the grid nodes (integer coordinates). 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 X, Y . Output For each test case, on a single line, print the number of such triangles. Example Input: 2 0 3 1 1 Output: 0 4 Constraints 1 <= T <= 10^4 0 <= X <= 10^4 0 <= Y <= 10^4 Information Your challenge is to give in time the answer with the shortest code. This problem is CT with more challenging constraints. Source limit is 512B My poorly golfed Py3 code scored 158B in 0.87s (for two input files). (time updated 2017-02-11 ; compiler changes)
34,751
Reliability of Logic Circuits (ZRELY1) Combinational logic circuits are part of all modern CPUs and other electronic means of information processing. These processors are widely used and constantly grow in complexity. Number of transistors in a modern CPU has exceeded 2 billion ? . And it looks like this growth does not tend to stop. At the same time, technological processes of processor production shrink. Transistors become smaller and more vulnerable to external influences. And now, even far from the strongest external radiation or magnetic field can lead to short-term changes in the logical values of microelectronic circuits. This problem is especially acute in space systems and other systems critical to reliability. In this problem, we pose the question, how to make the circuit more resilient to external influences knowing its logic? Your task is to develop an algorithm for creating such a reliable circuit. Let a logic circuit without feedback or memory elements is given, consisting of the following 6 elements: Name Description Operation Figure INV inverter OUT=!A AND logical «AND» OUT=A&B OR logical «OR» OUT=A|B NAND inverted AND OUT=!(A&B) NOR inverted OR OUT=!(A|B) XOR exclusive «OR» OUT=A^B The circuit is affected by environmental noise changing gate logical value to the opposite with a certain probability. Your task is to construct a circuit which has the same logic function as the original one, but is less prone to failures. Under the terms of the problem the circuit that you construct should exceed the initial area no more than "K" times . One of the parameters which characterize failure tolerance of logic circuits is COF – “Total circuit failure resistance factor”. COF is calculated as the ratio of the number of correct results of circuit performance (all circuit outputs must have correct value) to the total number of the performed tests. Accordingly, for the most reliable circuits COF tends to 1. Every logic gate of the circuit is characterized by the following parameters: S – gate area, p – failure probability (in percent) under current external conditions. Input data The first line shows Z – the number of tests ( Z < 400). This is followed by Z tests . The first line of each test shows the number K (2.0 ≤ K ≤ 20.0) - maximum circuit area redundancy. The following six lines contain two numbers each: area S (1 ≤ S ≤ 100) and failure probability q (0 ≤ q ≤ 20) in percent, Parameters of each of the logic gates are given in the following order: INV, AND, OR, NAND, NOR, XOR. The next line shows the number “ I ” (0 < I < 250) – the number of circuit inputs, followed by I lines, no more than 20 characters each, separated by spaces – the names of the input nodes of the circuit. The next line shows the number “ O ” (0 < O < 150) – the number of circuit outputs, followed by O lines, no more than 20 characters each, separated by spaces – the names of the output nodes of the circuit. Then the number of logic gates in the circuit N (1 < N < 5000) is stated, followed by N lines with the description of each gate. Description of each gate begins with its type, next come the names of the input nodes, then the name of the output node Output data For each test you should present the circuit description of in the following format. In the first line number N (1 < N < 100000) – the number of gates in the resulting circuit. This is followed by N – lines with the gates description. Each gate description begins with its type, next come the names of the input nodes, followed by the name of the output node. Scoring The number of scored points Score is summed over all tests. The number of points received for a test is equal to COF value calculated for your circuit. COF is calculated by Monte Carlo method ? in two steps: 1) in the first step, the judge determines that your circuit works identically to the original one. The same test sequences (several thousand) are fed to the inputs of both circuits and Boolean values at the outputs of the circuits are compared. If the logical values differ, you get the status of Wrong Answer. Also, the judge checks that the given circuit redundancy was not exceeded. 2) in the second step, the judge will invert the values on your circuit gates randomly with the given probability and compare the output values for your circuit and the benchmark circuit. If at least one of the outputs will be different, «wrong answers» counter will be increased. Formula used for calculation: COF = ( TT - INC )/ TT , where: TT - total number of tests INC - number of tests, where at least one output of the circuit manifested error From final score we extract C=276 points, which somewhere equal default soultion. If final score lower than 276 it'll recieve 0 points. Example Input data: Let logic circuit is given (see the figure). Required redundancy should not be more than 4.1 times. The circuit is based on the library, for which: INV has area 50 and failure probability 3% AND has area 60 and failure probability 3.1% OR has area 60 and failure probability 3.2% NAND has area 70 and failure probability 3.3% NOR has area 70 and failure probability 3.4% XOR has area 70 and failure probability 3.5% Input file for this task looks as follows: 1 5.1 50.0 3.0 60.0 3.1 60.0 3.2 70.0 3.3 70.0 3.4 70.0 3.5 2 a b 2 cs cc 5 INV a n1 INV b n2 NAND a b cc NAND n1 n2 n3 NAND n3 cc cs Output data: Let our algorithm uses standard triplication technique and selection of a Boolean value which is used on the majority of outputs (Triple Modular Redundancy (TMR) ? ). In this case, the output file can be written as follows: 25 INV a n1_a0 INV a n1_a1 INV a n1_a2 INV b n2_a0 INV b n2_a1 INV b n2_a2 NAND a b cc_a0 NAND a b cc_a1 NAND a b cc_a2 NAND n1_a0 n2_a0 n3_a0 NAND n1_a1 n2_a1 n3_a1 NAND n1_a2 n2_a2 n3_a2 NAND n3_a0 cc_a0 cs_a0 NAND n3_a1 cc_a1 cs_a1 NAND n3_a2 cc_a2 cs_a2 AND cs_a0 cs_a1 cs_3_0_and_0_out AND cs_a0 cs_a2 cs_5_0_and_0_out AND cs_a1 cs_a2 cs_6_0_and_0_out OR cs_3_0_and_0_out cs_5_0_and_0_out cs_0_or_0_out OR cs_0_or_0_out cs_6_0_and_0_out cs AND cc_a0 cc_a1 cc_3_0_and_0_out AND cc_a0 cc_a2 cc_5_0_and_0_out AND cc_a1 cc_a2 cc_6_0_and_0_out OR cc_3_0_and_0_out cc_5_0_and_0_out cc_0_or_0_out OR cc_0_or_0_out cc_6_0_and_0_out cc Figure for the resulting file Scoring: After simulation this solution will score 0.682661 points. Useful files: 1) Simple solution C/C++ - program reads the data and prints the circuit as it is, without changes. 2) Judge at C/C++ - program, which is used on the server for evaluation of the solution. Can be used locally to test the effectiveness of your solution. 3) Test data set - a set of 102 test circuits, similar to a set on the server.
34,752
Help Santa Claus to Pack the Toys (XMAS2014) English Indonesian One day, at the north pole there is a huge factory that produce many awesome toys. Santa Claus, who own this factory want to deliver this toys as a gift to many children who want some gift on christmas day using flying reindeer, because for each year number of toy increase and his flying reindeer get older, he want his load to be as light as possible. Fortunately this christmas (December 2014) he invent a new technology that can store infinite amount of toys using 4th space dimension, he call it "magical box", so every item/toys in magical box will weightless, very impressive! He invent that magical box on 23 December 2014, there still 2 days remaining before christmas, so he want to speed up the loading process. There are many toys to load in short time and his magical box can't absorb many obcect to 4th space dimension in short time, so he decided to split the work in parallel because he has many magical box available. For example if the toys numbered from 1 to n  first magical box absorb toy 2 to toy 5, ... , last magical box absorb toy n -7 to n -1. Note that it's possible that Santa's magical box can't absorb all toys in his factory on time even if he use parallel technique, so some toy maybe left in the factory for next christmas. Because his magical box still in "beta version" it still has a bug, it can only absorb consecutive toys only, so if toys 3 and toys 5 absorbed to same magical box, toy 4 will be accidentally absorbed to that magical box too. Since the problem become too complex, Santa want to rest and he left the factory to feed and tell his flying reindeer a good news that he invent the magical box so his flying reindeer will not carrying heavy load again like previous year. He also planning how he pack the toys to magical box. Because Santa is perfection, he want each box if used contains at least d toys. Now he wonder how many ways he can load the toys into his magical box if number of his magical box and number of toys in his factory is same. It's not necessary to use all his magical box, he want to use at least one of his magical box. Can you help him count how many ways he can do it? Input On the first line there is one integer c , denoting case type. For details about case type, see "Constraints". Each next line untill EOF there are three integers d , n , and m d = Minimal number of toys Santa want to put on each magical box n = Number of toys available at the Santa's factory m = Modulo, since the answer is very large, Santa will understand, he just need the answer modulo m . Output For each answer you get, output two numbers, d and the answer  modulo m in one line separated by a space. Constraints 2014 cases. 1 ≤ c ≤ 3 1 ≤ d ≤ 2014 (d will be unique on each input file, no two cases with same d) 1 ≤ m ≤ 10 9 Type1: 0 ≤ n < 2× d ; Score = 1 for each correct answer. Type2: 0 ≤ n ≤ max( d 2 ,2× d ); Score = 10 for each correct answer. Type3: 0 ≤ n < 2 64 ; Score = 100 for each correct answer. Scoring Your final score will be sum of score from test type1 to test type3. If you print all correct answers on test case type3 you'll get bonus score. Bonus score will be = floor{(25.0-[your time on test 3])*8056.0} Example 1 Input: 1 1 1 1000 2 3 1000 3 5 1000 4 7 1000 Output: 1 1 2 3 3 6 4 10 Score: Because this is input type 1, so each correct case worth 1 point. For this example score=4*1=4. Example 2 Input: 2 1 2 1000 2 4 1000 3 6 1000 4 8 1000 Output: 1 4 4 16 2 7 Score: Note that you can put your answer in any order, because there are 3 correct answers and this is input type 2 (each test case worth 10 points), for this example score=3*10=30. Example 3 Input: 2 1 2 1000 2 4 1000 3 6 1000 4 8 1000 Output: 1 4 3 10 4 16 2 7 Score: For this example you'll get "Wrong Answer". That's because for d=3 and n=6 and m=1000 answer should be 11, but output is 10. Better not output "3 10" like in example 2, than output wrong answer. For this example score = N/A. Example 4 Input: 3 1 11 1000 2 11 1000 Output: Score: Because user don't output anything score=0. Be careful, you'll get WA if sum of your score on test type1 to type3=0 Example 5 Input: 3 1 12345678987654321 1000 2 11 1000 Output: 2 23 Score: Because this is input type 3, so each correct case worth 100 points. For this example score=1*100=100 Example 6 Input: 3 1 3 5 2 4 6 Output: 1 2 2 1 1 2 Score: All answer are correct, but no duplicate d allowed, so for this example it will be judged as WA. Score for this example = N/A Example 7 Input: 3 1 3 1000000000 2 4 1000000000 Output: 1 12 2 7 Score: 200 Explanation for "Example 7" Here is 12 ways to pack 3 toys using 1 or more magical box and each magical box must contain minimal 1 toy. Here is 7 ways to pack 4 toys using 1 or more magical box and each magical box must contain minimal 2 toys. Additional Information All input ( n and m ) are generated with random uniform distribution in the range. My score at the time publication of this problem is 66554, Will it be hard to beat this(?) Update : [2014-12-24 13:42:56] Congratulations to Min_25 , first user who break my record in this problem. If some user has perfect score (223554) I'll not increase constraints or change test data, I'll change the scoring system (taking running time into account), but... will it happen? Update : It happen! [2015-01-02 22:38:52] Congratulations to Min_25 ! See also: Another problem added by Tjandra Satria Gunawan
34,753
Kejriwal And Broom (CDGLF1) Kejriwal And Broom   Once Kejriwal went to a sale of old brooms. There were ‘ n’ brooms at that sale. Broom with index ‘ i’ costs  ‘ai’ . Some brooms are so useless that they have a negative price ie. their owners are ready to pay Kejriwal if he buys those brooms. Kejriwal can buy any broom(s) he wants. Though he's very strong but  can carry at most ‘ m’ brooms only, and he has no desire to go to the sale for the second time. Please, help Kejriwal find out the maximum sum of money that he can earn. Input The first line contains ‘ t ’-number of test cases.Each test case contains two space-separated integers ‘ n’ and ‘ m’ — amount of brooms at the sale, and amount of brooms that Kejriwal can carry and the following line contains ‘ n’ space-separated integers ‘ ai’ — prices of the brooms Output Output the only number — the maximum sum of money that Kejriwal can earn, given that he can carry at most ‘ m’ brooms.   Constraints   1<=t<=100 1<=m<=n<=100 -1000<= ai<= 1000   Sample Input 2 5 3 -6 0 35 -2 4 4 2 7 0 0 -7   Sample Output 8 7
34,754
AAP Volunteers (CDGLF2) AAP Volunteers   After AAP’s massive victory in Delhi Assembly Elections 2015, AAP Volunteers have decided to clean the streets of delhi by collecting all the pamplets, caps, campaign material lying here and there and then putting them in the dustbin. There are ‘n’ different sites each having 1 bag full of these used materials and each bag has a certain value ‘Vi’ associated with it. A volunteer can travel only a certain distance ‘W’ at max. Suppose, site ‘i’ has a bag whose value is ‘Vi’ and the distance of that site from the dustbin is ‘Di’ , then the volunteer has to travel 2*Di distance (from dustbin to that site and from that site to the dustbin) and is thus able to earn ‘Vi’ points. Your task is to find out the maximum number of points that can be earned by the volunteer under the constraints that he can carry only 1 bag at a time and maximum distance that can be travelled by him is ‘W’ (in total).   Note: There is only one dustbin.   Input First line of input consists of ‘T’ denoting number of test cases .First line of each test case consists of ‘n’- number of sites and ‘W’-maximum distance that can be travelled by the volunteer in total. Second line consists of ‘n’ numbers( D1,D2,...,Dn) where ‘Di’ denotes the distance of that site from the dustbin and third line consists of ‘n’ numbers( V1,V2,...Vn) where ‘Vi’ denotes the value associated with the bag at the ‘i’th site.   Output Print the desired value on a separate line for each test case.   Constraints 1<=T<=50 1<=n<=10^3 1<=W<=10^3 1<=Vi<=10^8 1<=Di<=10^8   Sample Input 1 3 10 3 4 1 100 200 300   Sample Output 500
34,755
Mr Phoenix And OR Operation (CDGLF3) Mr Phoenix And OR Operation   Mr Phoenix has a sequence of ‘n’ non negative integers: A1,A2,A3,...,An. Mr CSI-DTU has invented a function F(l,r) {l,r, are non negative integers such that 1<=l<=r<=n)} and F(l,r)=Al | A(l+1) | A(l+2) |...| Ar. ie bitwise OR of all the elements with indexes from l to r.(both inclusive) Now, Mr Phoenix has decided to calculate the values of F(l,r) for all l, r such that 1<=l<=r<=n and he wants to know how many distinct values are there of F(l,r) . Help Mr Phoenix in finding out that count.   Input First line of input consists of ‘T’-number of test cases. First line of each test case consists of ‘n’-number of elements of the array and the second line consists of ‘n’ numbers .   Output Print the desired value corresponding to each test case on a single line.   Constraints 1<=T<=50 1<=n<=10^5 0<=Ai<=10^6   Sample Input 2 3 1 2 0 5 0 1 2 0 4   Sample Output 4 7
34,756
Majority Party (CDGLF4) Majority Party There are n houses in a locality. Every house gives a vote to a single party(say, AAP).(Party is denoted by a number). You are given queries (l to r) and asked to find if there exists a majority party in houses numbered from l to r. Note:A party is considered in majority if there exists a subarray of size > (size of range)/2 in which all votes are of the same party.(In case of odd , consider floor function). Input First line contains number n , the number of houses in the locality. Second line contains the n numbers denoting the party number of the vote of the ith house. Third line contains M which is the number of queries. M lines are given of the form l r.   Output   Output M lines containing the answer for each query in a single line. Answer of each query is of form "yes" or "no".   Constraints   n<=10^5 a[i]<=10^8 m<=10^5 1<=l<=r<=n   Sample Input   5 2 2 2 3 3 2 2 5 2 4   Sample Output   no yes
34,757
God Number is 20 (Rubik) (GODNIS20) The Rubik's cube is the most popular toy in the world. Some even consider it as sport, since it requires dedication and training to master it. Also, there are competitions all over the world. There are many ways to compete: 3x3x3 (Rubik's cube), 2x2x2, 3x3x3 blindfolded, 4x4x4, etc. Usually, a speed cuber takes between 50 and 60 move to solve it, using Fridrich method. Fridrich (or CFOP ) is a fast method, but requires a big effort for memorization. There are other methods like Roux (~48 moves), Petrus (~45 moves), ZZ (~50 moves) which requires fewer moves, but CFOP is still faster. There are other popular methods like Old Pochmann (~350 moves) ans M2/R2 (~150 moves). They are intended for blindsolving, since you can solve one piece at time.   A group of researches showed , by brute force, that any of the 43,252,003,274,489,856,000 positions of the Cube can be solved with at most 20 moves ( half turn metric ), now, "God Number is 20". The algorithm that always find the optimal solution for the cube is known as God's Algorithm, and it is just theoretical by these days.   Note: due to some abuses, in June 10th, 2016, a new judge was added. This one generates random cubes every time, although the n is fixed for every user. You can see the scrambles that generated the cubes you've got by clicking your score.   Input First line, you have n<100, the number of cubes to be solved. You will be given n valid scrambled cube position, as in the sample, with default orientation (white on top, green on front).   The cube's faces are represented like:  U LFRB  D   Ouput You have to output the length of your solution, then the solution (at most 1000 face turns). Any valid sequence that solves the cube will be accepted. If you want to skip a particular cube, you have to print "-1" instead of the solution length. The penalty for that is 1000 moves , although if you skip all the cases, you will get WA . Every move must be in HTM, without cube rotations or double rotations, i. e., the only accepted moves are {U, F, R, ...} and {U2, U', F2, F', ...}.   Score Score is the sum of the moves plus penaties.   Sample Input       W W W       W W W       O O O O O Y G G G W R R B B B O O Y G G G W R R B B B O O Y G G G W R R B B B       R R R       Y Y Y       Y Y Y       R W G       W W W       W W O G R R B G W B B W O O W O O O G G G R R R B B B O O O G G G R R R B B B       Y Y Y       Y Y Y       Y Y Y       G R B       O W G       O O G W G Y G Y W O R O W W R Y O O B G G Y R W O B B Y G R B Y B R W Y B R R       Y R W       W Y B       G B O 3       W W W       W W W       O O O O O Y G G G W R R B B B O O Y G G G W R R B B B O O Y G G G W R R B B B       R R R       Y Y Y       Y Y Y       R W G       W W W       W W O G R R B G W B B W O O W O O O G G G R R R B B B O O O G G G R R R B B B       Y Y Y       Y Y Y       Y Y Y       G R B       O W G       O O G W G Y G Y W O R O W W R Y O O B G G Y R W O B B Y G R B Y B R W Y B R R       Y R W       W Y B         G B O   Sample Output 1 F' 7 R U R' U R U2 R' -1   Sample Score 1008   (1+7+1000)   Special thanks to Mitch Schwartz , for helping in the custom judge, and Stefan Pochmann , for helping in some glitches.
34,758
lcm addition (ADDLCMS) Mao is very good in mathematics, he likes to play with numbers and number theory is his favorite chapter. Once he decided to give a question to kalyu his friend . Now Kalyu is always busy in writing articles, as he likes maths but articles is his passion and source of income too, so he can’t give much time solving that maths question, but he too don’t want to hurt his friend, so help kalu in his problem ? Given a,b such that a<=b  calculate the addition:-  LCM(a,b) + LCM(a+1,b) + .. + LCM(b,b), where LCM(a,b) denotes the Least Common Multiple of the integers a and b. Since, output may be very large, take the mod 10^9+7 Input First line cosists of T=number of test  cases, next T line will contain a and b Output For each T lines, print the required output. Constraints T<=100000 1 <= a <= b <= 1000000 Example Input: 3 1 6 10 15 41 90 Output: 66 675 139860 CHALLENGE : Minimum Source code
34,759
Lawnmower (LAWN) Dorian the Caretaker hates mowing the lawn. There is nothing worse than listening to this monotonous purr of the engine and inhaling its fumes for a few hours solid. Unfortunately, it just so happens that cutting the grass on the local millionaire's golf course is his only duty. But, fortunately for Dorian, salvation is here! His employer bought the newest miracle of engineering - Super Mower 3000, which can be remotely controlled. No more monotony, no more sweat and toil! Dorian will be finally fired, so he can start something he wanted to start for a long time - the search for a new job. No proper education and lack of prospects will only make it more fun. Super Mower 3000 has to be programmed beforehand, though. The golf course is a rectangle with n rows and m columns, which consists of square-shaped fields 1 meter wide. Some fields contain just grass, other fields have obstacles on them. Super Mower can instantly cut the grass just by being on the field. It cannot enter the field with an obstacle. Every grass-covered field is reachable from every other grass-covered field. Initially, Super Mower stands on the field in the first column of the first row, facing right. It executes a sequence of commands afterwards. There are four different commands: N - move one field forwards W - move one field backwards L - rotate 90 degrees left P - rotate 90 degrees right Moving one field forwards or backwards takes one second. Rotations are slower and take three seconds each. Given a description of the golf course, devise the sequence of commands that will make Super Mower mow the whole lawn (that is, it will visit every grass-covered field), while taking the least amount of time. Input The first line contains a single integer t , denoting the number of testcases. ( t <= 10). The descriptions of the testcases follow. First line of the description consists of two integers n and m (2 <= n , m <= 100), denoting the size of the golf course. Then n lines follow, each containg m characters. The j-th character in the i-th line describes the field in the i-th row and j-th column. "." (a dot) indicates a grass covered field, "#" indicates an obstacle. It is guaranteed that the first field is grass-covered. Output For each test case print one line with a string containing only letters "N", "L", "W" or "P", denoting the sequence of commands for Super Mower 3000 to execute. The sequence should make Super Mower visit every grass-covered field, without entering a field with an obstacle or going outside the course, and it cannot be longer than 16* n * m commands. Example Input: 2 4 7 ....... .##.##. .##.##. ....... 4 8 ........ ...#.### .#.#.... .#.#.... Output: NNNNNNPNNNPNNNPNNWWLNNNPNN NNNNNNNWWWPNNNLNNNLNLNNNPNNLNNLNNNWWPNNLNN Scoring If the sequence of commands satisfies all the conditions given in the problem statement, and it takes x seconds to execute, it is worth x /( n * m ) points. Overall score is equal to the sum of individual scores. Sample test explanation The first sequence takes 36 seconds to execute, the second sequence takes 60 seconds. Then, your score is 36/(4*7) + 60/(4*8), so about 3.16.
34,760
Hieroglyphs (HIE) Archibald the Archeologist is on the trail of a great mystery! This mystery is so great, and deals with such important matters, that solving it would surely cause a massive uproar in the communities of archeologists and computer scientists alike. Whole textbooks would have to be rewritten from scratch, from "Introduction to archeology" to "Algorithms and data structures". That's what Archibald claims, anyway. But most of the scientific world considers him insane since the Rosetta Stone incident (which allegedly contained pseudocode of Dijkstra's algorithm). This time, he claims the existence of previously unknown, ancient South American La-Og-Mhtir civilization - moreover, he has the evidence to support that claim. Their temple, hidden somewhere in the underground of the Amazon rainforests, supposedly contains boundless amounts of ideas, and revealing them would lead to several breakthroughs in computer science. Archibald proposes a bold thesis that even P=NP problem was already solved by this civilization, and the proof (which is elegant and ingenious) can be found somewhere in the heart of their shrine. La-Og-Mhtirs' temple is really well hidden - despite multitude of hints that Archibald found during many years of his studies, he still can't pinpoint its exact location. It looks like this time he is really close, though! During his expedition in the Central Andes in Chile, he found some ancient tablets. There is an inscription above the entrance to the chapel: "Fastest solution will be found only by the ingenious one", and it uses very characteristic symbols of the La-Og-Mhtirs' alphabet (which, by sheer luck, has 26 letters, just like the English alphabet). Archibald carefully examined two biggest tablets on the inner wall of the chapel. Both contained n rows of letters, and there were n letters in each row. He also found a bizarre mechanism behind the first one! By tinkering with some buttons (made from stone), Archibald can turn any letter on the first tablet into another one from the alphabet - but it takes a long time ( n 2 hours). After further examination it turned out that another set of buttons can be found near the chapel's ceiling - by using them, it is possible to choose a square-shaped area inside the tablet, and rotate it by 90 degrees (clockwise or counterclockwise) - and it only takes one hour! For no apparent reason, chosen square has to be at least 5 letters wide. As an example: in the picture above, by choosing a 5x5 square with top left corner in the second row and the second column of the first tablet, and rotating it counterclockwise, we obtain the second tablet. Rows and columns are numbered from 1 to n , from top to bottom and from left to right. Finally, the mystery gradually uncovers itself, right before the Archibald's eyes. Devoting whole life to studying various hints, scattered throughout the world, is starting to pay off. The only thing left to do for Archibald is to use the mechanisms, and make the first tablet look exactly like the second one. More than that - it has to be done as quickly as possible. If La-Og-Mhtirs will deem his solution worthy, the chapel will reveal the location of the Great Temple. Input The first line contains a single integer t , denoting the number of testcases. ( t <= 10). The descriptions of the testcases follow. The first line of the description contains a single integer n - size of the tablets. (5 <= n <= 30). Then the descriptions of the two tablets follow. The description of a single tablet consists of n lines, each containing n uppercase letters of English alphabet (which correspond to appropriate letters of La-Og-Mhtirs' alphabet). The j-th character in the i-th line describes the i-th row and j-th column of the tablet. Output For each testcase you should find a sequence of moves that will turn the first tablet into the second one. The sequence starts with two integers m and k (0 <= m <= n 3 , 0 <= k <= n 4 ), denoting the number of moves in the sequence and the time needed to execute that sequence in hours, respectively. Then you should output the descriptions of the m moves. The description of one move starts with a string "Z", "OL", or "OP", denoting changing one letter, rotating a square counterclockwise and rotating a square clockwise, respectively. For a "Z" move, you should then output two integers r , c and a single character of the English alphabet x (1 <= r , c <= n ). It denotes changing the letter in the r -th row and c -th column to x . For a "OL" or "OP" move, you should then output three integers r , c , q . (1 <= r , c <= n , 5 <= q <= n ). It denotes a rotation of the square that is q letters wide, with top left corner in the r -th row and the c -th column. Given square should be completely contained inside the tablet. Example Input: 1 6 AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF AAAAAA BBCDEF CBCDEF DBCDEF EBCDEF FBCDEX Output: 2 37 OL 2 2 5 Z 6 6 X Scoring If the sequence of moves satisfies all the conditions given in the problem statement, and k is computed correctly, it is worth k /( n 4 ) points. Overall score is equal to the sum of individual scores. Sample testcase explanation First operation rotates a square 5 letters wide, with its top left corner in (2,2). This operation takes 1 hour to execute. Second operation changes the letter in the sixth row and the sixth column to "X", which takes 6 2 hours to execute. Then, the total score is (1+6 2 )/(6 4 ) which is about 0.029.
34,761
Seedlings (SEE) Bogdan the Botanist is conducting research on a certain species of plant, which supposedly have some miraculous healing properties. Thanks to his connections among other scientists, he can get as many seedlings for his research as he pleases. However, plants need proper conditions in order to grow properly. The best method to ensure that seedlings develop correctly is to place them on specialized shelves, which have proper watering systems, lighting conditions etc. Many different shapes of the shelves are available. Apart from the standard square-shaped 1x1 shelves, it is also possible to obtain shelves that look like this: Each of the shelves presented above consists of four standard-shaped shelves. Standard shelf can hold one large flowerpot with seedlings. Shelves presented above can hold six flowerpots, thanks to somewhat better use of available space. Bogdan already bought a room for storing the seedlings - from birds eye view, it looks like a rectangle, n meters high and m meters wide, consisting of square-shaped fields, each 1 meter wide. You can't place the shelves on some of the fields (due to wiring, water supply systems and other stuff) - we consider such fields blocked. There is a door on the wall above the field in the top left corner - it opens inward, so we can't place anything on this field either. Bogdan plans to fit as many flowerpots in the room as possible, by placing shelves on the remaining fields. Moreover, he wants to do it in such a way that the square-shaped segments of the shelves exactly cover the fields in the room. His research demands constant access to plants - every shelf must be accessible by walking on non-blocked fields, starting from the field with the door. You can walk between two fields if they share a common edge. Help Bogdan! Place the shelves according to the rules, to fit as many flowerpots in the room as possible. Input The first line contains a single integer t , denoting the number of testcases. ( t <= 10). Then, testcases follow. The description of a single testcase begins with two integers n , m (1 <= n , m <= 50) - height and width of the rectangle representing the room. Then, n lines follow, each containing m characters. j -th character in i -th line denotes a square in i -th row nad j -th column. "." (a dot) denotes free square, "X" denotes blocked square. Field in the top left corner is always free. Output For every testcase you should find an arrangement of shelves that satisfies the rules from the problem statement. The descriptions begins with two integers p and d (1 <= p <= n * m ) - number of shelves and number of flowerpots on the shelves, respectively. Then, the descriptions of p shelves should follow. Each shelf is described by four integers w i , k i , r i and o i (1 <= w i <= n , 1 <= k i <= m , 0 <= r i <= 7, 0 <= o i <= 3) - it means that the anchor point of the i -th shelf is in the row number w i and column number k i , the shelf is of type r i , and is rotated o i times 90 degrees to the right, starting from the configuration on the picture. Anchor point of every shape is in the top left corner in the picture (and it is in the same segment after the rotation). Type 0 denotes standard 1x1 square-shaped shelf, types from 1 to 7 correspond to shapes in the picture (counting from left to right). Example Input: 1 4 5 ..... ....X .X... ...X. Output: 4 19 1 2 1 3 2 4 6 0 3 3 5 1 3 1 0 0 Explanation The arrangement from the sample testcase looks as follows: You can't place another shelf without violating the rules - for example, by putting type 0 shelf on the field at (2,3), the red shelf and the green shelf would be unreachable. The arrangement contains three larger shelves and one standard shelf, so the total number of flowerpots is 3*6+1 = 19. Scoring If the arrangement of the shelves is correct, and the given number of flowerpots d is correct, it is worth d /( n * m ) points. Overall score is equal to the sum of individual scores. Score for the sample output is 19/(4*5) = 0.95.
34,762
Simple Numbers Conversion (TCONNUM) Every integer number n is represented in positional number system of base r by a sequence of digits 0 ≤ d i < r , so the value is equal to: n = d 0   + r * d 1 + r 2 * d 2 + r 3 * d 3 + ... Your task is to convert a given number in r -base represantation into s -base representation, for example: decimal 231 into binary 11100111. Assume that r ≤ 36 and the digits are 0,1,2,3,4,5,6,7,8,9, A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , U , V , W , X , Y , Z . Input N [the number of series ≤ 1000] n r s [ n ≤ 10 1000 , r , s ≤ 36] Output n [ s -base representation of number n ] Text grouped in [ ] does not appear in the input and output file. Example Input: 3 231 10 2 ABC 15 10 XYZ 36 2 Output: 11100111 2427 1010101111111011 Test cases There are five categories of the input data: Test case 1: (1 pt), r = 2 and s = 10, or conversely, n ≤ 10 9 , N = 100, Test case 2: (1 pt), 2 ≤ r , s ≤ 10, n ≤10 9 , N = 1000, Test case 3: (1 pt), 2 ≤ r , s ≤ 36, n ≤ 10 9 , N = 1000, Test case 4: (3 pts), 2 ≤ r , s ≤ 10, n ≤ 10 1000 , N = 1000, Test case 5: (4 pts), 2 ≤ r , s ≤ 36, n ≤ 10 1000 , N = 1000.
34,763
Longest Common Subsequence (TLCS) Wersja polska English version For a given two words x = x 1 x 2 ...x n and y = y 1 y 2 ...y m find the longest common subsequence, i.e. z = z 1 z 2 ...z k such that every two consecutive elements of z are equal to some two elements of x : x a , x b , and y : y c , y d where a < b and c < d . Assume, that elements of words are letters 'a' - 'z' and m , n <= 1000. Input N [the number of series <= 1000] n x m y ... Output case 1 Y [or N when no answer to this case] d [the length of the lcs] z j p q [position of z j in x and in y , respectively] ... Text grouped in [ ] does not appear in the input and output file. Example Input: 3 5 ddacc 3 cac 7 cbbccbc 4 aaca 4 cbeb 5 fdceb Output: case 1 Y 2 a 3 2 c 4 3 case 2 N case 3 Y 3 c 1 3 e 3 4 b 4 5 Score 2
34,764
The Ants in a Tree (PT07I) In Amber's childhood, he usually liked to observe some little things for tickling his little curiosity. He often found it interesting to climb up a tree, sit on a branch and watch the movement of a group of lovely ants on the branches of the tree. Amber finds there are n ant holes and m ants in the tree now. Because of his careful observation, he knows all ants' behaviors, the i -th ant wanna travel from one hole s i to another hole t i at the speed v i . During the ant's travel, if two ants arrive at the same position (meet or chase), they will touch their feelers for exchanging the information about food or danger. Even at the moment that the travel starts or finishes, the ant can also touch other's feelers. But after the travel finishes, the ant will enter into the hole and never touch feelers. What amber wonders is to count the times of touchings during the whole traveling process. Consider there are n - 1 branches in the tree. Each branch connects the adjacent ant holes and has a particular length. Assume there is always a path that consists of branches between any two ant holes. Assume that no two ants have the same speeds and the touching doesn't cost any time. Input Input consists of multiple testcases. The first line contains one integer t (1 <= t <= 20). For each testcase, the input format is following. The first line contains one integer n (1 <= n <= 10 6 ). In next n - 1 line, the i -th line contains an integer triple ( u i , v i , w i ) (1 <= u i , v i <= n , u i != v i , 1 <= w i <= 10 3 ). The triple means there is a branch with the length w i between node u i and node v i . The next line contains one integer m (1 <= m <= 10 3 ). In next m line, the i -th line contains an integer triple ( s i , t i , v i ) (1 <= s i , t i <= n , 1 <= v i <= 10 6 ). The triple means that the i -th ant's travel is from s i to t i at the speed v i . Output For each testcase, print a line that consists of an integer that means the times of the feeler touchings. Example Input: 1 3 1 2 1 2 3 1 3 1 3 1 3 1 1 1 2 3 Output: 2 Note: It's a partly correct problem, so score is set for each case. When you pass all cases, you'll get 300 points
34,765
Leaves (NKLEAVES) English Vietnamese One beautiful autumn day Radu and Mars noticed that the garden alley where they usually spend time is rather full of leaves. They decided to gather all the leaves in exactly K piles. The alley is a straight line and they established a coordinate system on the alley, with the origine at the beginning of the alley. There are N leaves of various weights on the alley, all lined up, and the distance between each consecutive leaves is 1. More precisely the first leaf is at coordinate 1, the second at coordinate 2, ... , the N-th at coordinate N. Initially the two guys are at coordinate N. The leaf gathering operation takes place as Radu and Mars leave the garden, so the leaves can only be moved to the left. The cost of moving a leaf is equal to its weight times the distance it is moved. Obviously one of the K piles will be at coordinate 1, but the rest can be anywhere. Task Find out the total minimum cost of gathering the N leaves in exactly K piles. Input The input contains on the first line two positive integers, N and K, separated by a space, having the significance given above. The following N lines contain N positive integers representing the weights of the leaves (line i+1 contains the weight of the leaf located at coordinate i). Output The output will contain a single line on which the minimum cost for gathering all the leaves in exactly K piles will be written. Constraints 0 < N < 100 001 0 < K < 11, K < N 0 < the weight of any leaf < 1 001 Example Input 5 2 1 2 3 4 5 Output 13 It would be best to form the 2 piles in points 1 and 4. Leaves 1, 2 and 3 are taken to coordinate 1, and 4 and 5 are taken to coordinate 4. The total cost is: 1 * 0 + 2 * 1 + 3 * 2 + 4 * 0 + 5 * 1 = 13
34,766
Mars Map (NKMARS) English Vietnamese (This task was inspired by task ‘Atlantis’ of the Mid–Central European Regional ACM–ICP Contest 2000/2001.) In the year 2051, several Mars expeditions explored different areas of the red planet and produced maps of these areas. Now, the BaSA (Baltic Space Agency) has an ambitious plan: they would like to produce a map of the whole planet. In order to calculate the necessary effort, they need to know the total size of the area for which maps already exist. It is your task to write a program that calculates this area. Input The input starts with a line containing a single integer N (1 ≤ N ≤ 10 000 ), the number of available maps. Each of the following N lines describes a map. Each of these lines contains four integers x 1 , y 1 , x 2 and y 2 (0 ≤ x 1 < x 2 ≤ 30 000 , 0 ≤ y 1 < y 2 ≤ 30 000 ). The values ( x 1 ;y 1 ) and ( x 2 ;y 2 ) are the coordinates of, respectively, the bottom-left and the top- right corner of the mapped area. Each map has rectangular shape, and its sides are parallel to the x- and y-axis of the coordinate system. Output The output should contain one integer A, the total area of the explored territory (i.e. the area of the union of all the rectangles). Example Input 2 10 10 20 20 15 15 25 30 Output 225
34,767
Team Selection (NKTEAM) English Vietnamese The Interpeninsular Olympiad in Informatics is coming and the leaders of the Balkan Peninsula Team have to choose the best contestants on the Balkans. Fortunately, the leaders could choose the members of the team among N very good contestants, numbered from 1 to N (3 ≤ N ≤ 500000). In order to select the best contestants the leaders organized three competitions. Each of the N contestants took part in all three competitions and there were no two contestants with equal results on any of the competitions. We say that contestant А is better than another contestant В when А is ranked before В in all of the competitions. A contestant A is said to be excellent if no other contestant is better than A. The leaders of the Balkan Peninsula Team would like to know the number of excellent contestants. Write a program, which for given N and the three competitions results, computes the number of excellent contestants. Input The input data are given as four lines. The first line contains the number N. The next three lines show the rankings for the three competitions. Each of these lines contains the identification numbers of the contestants, separated by single spaces, in the order of their ranking from first to last place. Output The output should contain one line with a single number written on it: the number of the excellent. Example Input 3 2 3 1 3 1 2 1 2 3 Output 3 Note: No contestant is better than any other contestant, hence all three are excellent. Input 10 2 5 3 8 10 7 1 6 9 4 1 2 3 4 5 6 7 8 9 10 3 8 7 10 5 4 1 2 6 9 Output 4 Note: The excellent contestants are those numbered with 1, 2, 3 and 5.
34,768
IOI01 Mobiles (NKMOBILE) English Vietnamese Suppose that the fourth generation mobile phone base stations in the Tampere area operate as follows. The area is divided into squares. The squares form an SxS matrix with the rows and columns numbered from 0 to S - 1. Each square contains a base station. The number of active mobile phones inside a square can change because a phone is moved from a square to another or a phone is switched on or off. At times, each base station reports the change in the number of active phones to the main base station along with the row and the column of the matrix. Write a program, which receives these reports and answers queries about the current total number of active mobile phones in any rectangle-shaped area. Input The input is encoded as follows. Each input comes on a separate line, and consists of one instruction integer and a number of parameter integers according to the following table. Instruction Parameters Meaning 0 S Initialize the matrix size to S´S containing all zeros. This instruction is given only once and it will be the first instruction. 1 X Y A Add A to the number of active phones in table square (X, Y). A may be positive or negative. 2 L B R T Query the current sum of numbers of active mobile phones in squares (X,Y), where L ≤ X ≤ R, B ≤ Y ≤ T 3 . Terminate program. This instruction is given only once and it will be the last instruction. The values will always be in range, so there is no need to check them. In particular, if A is negative, it can be assumed that it will not reduce the square value below zero. The indexing starts at 0, e.g. for a table of size 4x4, we have 0 ≤ X ≤ 3 and 0 ≤ Y ≤ 3. Output Your program should not answer anything to lines with an instruction other than 2. If the instruction is 2, then your program is expected to answer the query by writing the answer as a single line containing a single integer. Constraints 1 ≤ S ≤ 1024. Cell value V at any time: 0 ≤ V ≤ 2 15 –1 (= 32767). Update amount A: -32768 ≤ A ≤ 32767. Number of instructions in input U: 3 ≤ U ≤ 60002. Maximum number of phones in the whole table M=2 30 Example Input 0 4 1 1 2 3 2 0 0 2 2 1 1 1 2 1 1 2 -1 2 1 1 2 3 3 Output 3 4
34,769
IOI05 Mountains (NKMOU) English Vietnamese The Mountain Amusement Park has opened a brand-new simulated roller coaster. The simulated track consists of n rails attached end-to-end with the beginning of the first rail fixed at elevation 0. Byteman, the operator, can reconfigure the track at will by adjusting the elevation change over a number of consecutive rails. The elevation change over other rails is not affected. Each time rails are adjusted, the following track is raised or lowered as necessary to connect the track while maintaining the start at elevation 0. The figure below illustrates two example track reconfigurations. Each ride is initiated by launching the car with sufficient energy to reach height h. That is, the car will continue to travel as long as the elevation of the track does not exceed h, and as long as the end of the track is not reached. Given the record for all the day’s rides and track configuration changes, compute for each ride the number of rails traversed by the car before it stops. Internally, the simulator represents the track as a sequence of n elevation changes, one for each rail. The i-th number d i represents the elevation change (in centimetres) over the i-th rail. Suppose that after traversing i−1 rails the car has reached an elevation of h centimetres. After traversing i rails the car will have reached an elevation of h+d i centimetres. Initially the rails are horizontal; that is, d i = 0 for all i. Rides and reconfigurations are interleaved throughout the day. Each reconfiguration is specified by three numbers: a, b and D. The segment to be adjusted consists of rails a through b (inclusive). The elevation change over each rail in the segment is set to D. That is, d i = D for all a ≤ i ≤ b. Each ride is specified by one number h — the maximum height that the car can reach. Input The first line of input contains one positive integer n — the number of rails, 1 ≤ n ≤ 1 000 000 000 . The following lines contain reconfigurations interleaved with rides, followed by an end marker. Each line contains one of: Reconfiguration — a single letter ‘I’, and integers a, b and D, all separated by single spaces (1 ≤ a ≤ b ≤ n, −1 000 000 000 ≤ D ≤ 1 000 000 000 ). Ride — a single letter ‘Q’, and an integer h (0 ≤ h ≤ 1 000 000 000) separated by a single space; A single letter ‘E’ — the end marker, indicating the end of the input data. You may assume that at any moment the elevation of any point in the track is in the interval [0 ,1 000 000 000] centimetres. The input contains no more than 100 000 lines. In 50% of test cases n satisfies 1 ≤ n ≤ 20 000 and there are no more than 1 000 lines of input. Output The i-th line of output should consist of one integer — the number of rails traversed by the car during the i-th ride. Example Input 4 Q 1 I 1 4 2 Q 3 Q 1 I 2 2 -1 Q 3 E Output 4 1 0 3 Views of the track before and after each reconfiguration. The x axis denotes the rail number. The y axis and the numbers over points denote elevation. The numbers over segments denote elevation changes.
34,770
IOI07 Pairs (NKPAIRS) English Vietnamese Mirko and Slavko are playing with toy animals. First, they choose one of three boards given in the figure below. Each board consists of cells (shown as circles in the figure) arranged into a one, two or three dimensional grid. Mirko then places N little toy animals into the cells. The distance between two cells is the smallest number of moves that an animal would need in order to reach one cell from the other. In one move, the animal may step into one of the adjacent cells (connected by line segments in the figure). Two animals can hear each other if the distance between their cells is at most D . Slavko's task is to calculate how many pairs of animals there are such that one animal can hear the other. Task Write a program that, given the board type, the locations of all animals, and the number D, finds the desired number of pairs. Input The first line of input contains four integers in this order: The board type B (1 ≤ B ≤ 3); The number of animals N (1 ≤ N ≤ 100 000); The largest distance D at which two animals can hear each other (1 ≤ D ≤ 100 000 000); The size of the board M (the largest coordinate allowed to appear in the input): When B=1, M will be at most 75 000 000. When B=2, M will be at most 75 000. When B=3, M will be at most 75. Each of the following N lines contains B integers separated by single spaces, the coordinates of one toy animal. Each coordinate will be between 1 and M (inclusive). More than one animal may occupy the same cell. Output Output should consist of a single integer, the number of pairs of animals that can hear each other. Note: use a 64-bit integer type to calculate and output the result (long long in C/C++, int64 in Pascal). Grading In test cases worth a total of 30 points, the number of animals N will be at most 1000. Furthermore, for each of the three board types, a solution that correctly solves all test cases of that type will be awarded at least 30 points. Example Input 1 6 5 100 25 50 50 10 20 23 Output 4 Input 2 5 4 10 5 2 7 2 8 4 6 5 4 4 Output 8 Input 3 8 10 20 10 10 10 10 10 20 10 20 10 10 20 20 20 10 10 20 10 20 20 20 10 20 20 20 Output 12
34,771
Lubenica (LUBENICA) English Vietnamese The traffic network in a country consists of N cities (labeled with integers from 1 to N) and N-1 roads connecting the cities. There is a unique path between each pair of different cities, and we know the exact length of each road. Write a program that will, for each of the K given pairs of cities, find the length of the shortest and the length of the longest road on the path between the two cities. Input The first line of input contains an integer N, 2 ≤ N ≤ 100 000. Each of the following N-1 lines contains three integers A, B and C meaning that there is a road of length C between city A and city B. The length of each road will be a positive integer less than or equal to 1 000 000. The next line contains an integer K, 1 ≤ K ≤ 100 000. Each of the following K lines contains two different integers D and E – the labels of the two cities constituting one query. Output Each of the K lines of output should contain two integers – the lengths from the task description for the corresponding pair of the cities. Example Input 1 6 5 100 25 50 50 10 20 23 Output 100 200 50 150 50 100 Input 7 3 6 4 1 7 1 1 3 2 1 2 6 2 5 4 2 4 4 5 6 4 7 6 1 2 1 3 3 5 Output 2 6 1 4 6 6 2 2 2 6 Input 9 1 2 2 2 3 1 3 4 5 2 7 4 1 5 3 5 6 1 5 9 2 1 8 3 5 6 9 7 8 9 4 1 2 7 3 Output 1 2 2 4 1 5 2 2 1 4
34,772
Police (NKPOLICE) English Vietnamese To help capture criminals on the run, the police are introducing a new computer system. The area covered by the police contains N cities and E bidirectional roads connecting them. The cities are labelled 1 to N. The police often want to catch criminals trying to get from one city to another. Inspectors, looking at a map, try to determine where to set up barricades and roadblocks. The new computer system should answer the following two types of queries: Consider two cities A and B, and a road connecting cities G1 and G2. Can the criminals get from city A to city B if that one road is blocked and the criminals can't use it? Consider three cities A, B and C. Can the criminals get from city A to city B if the entire city C is cut off and the criminals can't enter that city? Write a program that implements the described system. Input The first line contains two integers N and E (2 ≤ N ≤ 100 000, 1 ≤ E ≤ 500 000), the number of cities and roads. Each of the following E lines contains two distinct integers between 1 and N – the labels of two cities connected by a road. There will be at most one road between any pair of cities. The following line contains the integer Q (1 ≤ Q ≤ 300 000), the number of queries the system is being tested on. Each of the following Q lines contains either four or five integers. The first of these integers is the type of the query – 1 or 2. If the query is of type 1, then the same line contains four more integers A, B, G1 and G2 as described earlier. A and B will be different. G1 and G2 will represent an existing road. If the query is of type 2, then the same line contains three more integers A, B and C. A, B and C will be distinct integers. The test data will be such that it is initially possible to get from each city to every other city. Output Output the answers to all Q queries, one per line. The answer to a query can be "yes" or "no". Example Input 13 15 1 2 2 3 3 5 2 4 4 6 2 6 1 4 1 7 7 8 7 9 7 10 8 11 8 12 9 12 12 13 5 1 5 13 1 2 1 6 2 1 4 1 13 6 7 8 2 13 6 7 2 13 6 8 Output yes yes yes no yes
34,773
IOI07 Miners (NKMINERS) English Vietnamese There are two coal mines, each employing a group of miners. Mining coal is hard work, so miners need food to keep at it. Every time a shipment of food arrives at their mine, the miners produce some amount of coal. There are three types of food shipments: meat shipments, fish shipments and bread shipments. Miners like variety in their diet and they will be more productive if their food supply is kept varied. More precisely, every time a new shipment arrives to their mine, they will consider the new shipment and the previous two shipments (or fewer if there haven't been that many) and then: If all shipments were of the same type, they will produce one unit of coal. If there were two different types of food among the shipments, they will produce two units of coal. If there were three different types of food, they will produce three units of coal. We know in advance the types of food shipments and the order in which they will be sent. It is possible to influence the amount of coal that is produced by determining which shipment should go to which mine. Shipments cannot be divided; each shipment must be sent to one mine or the other in its entirety. The two mines don't necessarily have to receive the same number of shipments (in fact, it is permitted to send all shipments to one mine). Task Your program will be given the types of food shipments, in the order in which they are to be sent. Write a program that finds the largest total amount of coal that can be produced (in both mines) by deciding which shipments should be sent to mine 1 and which shipments should be sent to mine 2. Input The first line of input contains an integer N (1 ≤ N ≤ 100 000), the number of food shipments. The second line contains a string consisting of N characters, the types of shipments in the order in which they are to be distributed. Each character will be one of the uppercase letters 'M' (for meat), 'F' (for fish) or 'B' (for bread). Output Output a single integer, the largest total amount of coal that can be produced. Grading In test cases worth a total of 45 points, the number of shipments N will be at most 20. Example Input 6 MBMFFB Output 12 Input 16 MMBMBBBBMMMMMBMB Output 29
34,774
Monkey island (NKTRAFIC) English Vietnamese After they divided the country into counties the monkeys have a new problem: they have to stop the banana traffic. Monkey Land has N cities numbered from 1 to N connected by M two-directional roads. Between each two cities there is at most one road but between any to cities there is at least one connecting path (made up of one ore more roads). Cities 1 and N are capitals. Lately, the banana traffic between the two capitals has increased. In order to fight the traffic the president has G soldiers he can place anywhere on a road, no matter how close to a city, but not inside a city. In case of an attack on one of the capitals all soldiers must get to that capital. Soldiers move at the same constant speed. The amount of time required for such a mobilization is equal to the maximum distances from the soldiers to one of the capitals. Task Write a program that finds a soldier placement solution so that any path from one capital to the other go through at least one road with a soldier and the mobilization time for the worst case scenario be minimal. Input The input contains on the first line three integers N M G separated by blanks. Each of the following M lines contains three integers separated by blanks a b c meaning "there is a two-way road between city a and b of length c". Output The output will contain a single line with the minimum time needed for all the soldiers to get to a capital, written with one exact decimal. If there is no solution, the first line will contain -1. Constraints 2 < N < 155 2 < M < 5055 0 < the length of any road < 1024 2 < G < 4096 Example Input 6 6 2 1 2 1 2 3 2 3 6 1 1 4 1 4 5 3 5 6 1 Output 2.5
34,775
Billboard painting (NKPANO) English Vietnamese A group of K painters has to paint a rectangular billboard of size 1xN. The billboard is divided into N cells of size 1x1. The cells are numbered from 1 to N in left to right order. The i-th painter (1 ≤ i ≤ K) is currently standing in front of the cell S i . He either can paint no cells at all or can paint a consecutive number of cells that must containt the cell S i . Moreover, he can only paint at most L i cells, and for each painted cell, he will receive a payment of P i dollars. Each cell can be painted by at most one person. Your task is to find a way for the painters to receive the largest amount of payment. Input The first line of the input contains two positive integers N, K (N ≤ 16000; K ≤ 100). The i-th line of the next K lines contains three positive integers L i , P i , S i (i = 1, 2, … K) separated by spaces (1 ≤ P i ≤ 10000, 1 ≤ L i , S i ≤ N ). The numbers S 1 , S 2 , . . . S K are pairwise distinct. Output A single line contains the largest payment that the painters can receive. Example Input 8 4 3 2 2 3 2 3 3 3 5 1 1 7 Output 17 The first painter will paint the first two cells, the second painter will paint the next two cells, the third one will paint the remaining cells and the last won't have to paint any cells.
34,776
Distance (NKDIST) English Vietnamese Consider a sequence D consisting of an infinite number of hexadecimal digits made by concatenating all the positive integers 1, 2, 3, 4,..., N,... The sequence D begins with: 123456789ABCDEF10111 21 31415161718191A1B1C1D1E1F20 21 22... We may see D as an infinite string of hexadecimal digits. Let S be an arbitrary string consisting only of hexadecimal digits. The number of occurrences of S in D as a substring is infinite. The distance between two nonoverlapping occurrence of S is the number of digits between these two occurrences. For instance, if S='21', the distance between the first two occurrences of S is 27 (as illustrated above). Task You are given a string S of at most 30 characters long. Write a program that determines the distance between the first two occurrences of S in D. Input The input contains the string S in a single line. Output The output contains the distance between the first two occurrences of S in D in a single line. Example Input 21 Output 27 Input A Output 26
34,777
Triangles (VTRI) English Vietnamese In the plane, given a rectangular grid with sides parallel to the axes of coordinates. The coordinates of the bottom-left corner is (0, 0) and the top-right corner is (X, Y). Your task is to count the number of triangles with integer coordinates lying inside the given grid and having areas equal to an integer S. Input A single line consisting of three integers: X, Y, S (1 ≤ X, Y ≤ 30, 1 ≤ S ≤ X*Y/2). Output A single integer: the number of triangles with integer coordinates lying inside the rectanglular grid and having areas equal to S. Constraint There are 50% of the test cases, corresponding to 50% of the grades, in which 1≤X, Y≤10. Example Input 2 1 1 Output 6
34,778
Query on a tree again! (QTREE3) English Vietnamese You are given a tree (an acyclic undirected connected graph) with N nodes. The tree nodes are numbered from 1 to N. In the start, the color of any node in the tree is white. We will ask you to perfrom some instructions of the following form: 0 i : change the color of the i-th node (from white to black, or from black to white); or 1 v : ask for the id of the first black node on the path from node 1 to node v. if it doesn't exist, you may return -1 as its result. Input In the first line there are two integers N and Q . In the next N -1 lines describe the edges in the tree: a line with two integers a b denotes an edge between a and b . The next Q lines contain instructions "0 i" or "1 v" (1 ≤ i, v ≤ N). Output For each " 1 v " operation, write one integer representing its result. Example Input: 9 8 1 2 1 3 2 4 2 9 5 9 7 9 8 9 6 8 1 3 0 8 1 6 1 7 0 2 1 9 0 2 1 9 Output: -1 8 -1 2 -1 Constraints & Limits There are 12 real input files. For 1/3 of the test cases, N=5000, Q=400000. For 1/3 of the test cases, N=10000, Q=300000. For 1/3 of the test cases, N=100000, Q=100000.
34,779
Triangles 2 (VTRI2) English Vietnamese Triangle 2 (This is a bonus problem. You will get a maximum score of 30 from this one) This problem description is the same as the problem VTRI except that in all test cases 200 ≤ X, Y ≤ 250. The result will fit in a 64-bit integer. Example Input 200 200 1 Output 1488042840
34,780
Copier Reduction (REDUCT) What do you do if you need to copy a 560x400mm image onto a standard sheet of US letter-size paper (which is about 216x280mm), while keeping the image as large as possible? You can rotate the image 90 degrees (so that it is in landscape mode), then reduce it to 50% of its original size so that it is 200x280mm.Then it will fit on the paper without overlapping any edges. Your job is to solve this problem in general. Input The input consists of one or more test cases, each of which is a single line containing four positive integers A , B , C , and D , separated by a space, representing an A x B mm image and a C x D mm piece of paper. All inputs will be less than one thousand. Following the test cases is a line containing four zeros that signals the end of the input. Output For each test case, if the image fits on the sheet of paper without changing its size (but rotating it if necessary), then the output is 100%. If the image must be reduced in order to fit, the output is the largest integer percentage of its original size that will fit (rotating it if necessary). Output the percentage exactly as shown in the examples below. You can assume that no image will need to be reduced to less than 1% of its original size, so the answer will always be an integer percentage between 1% and 100%, inclusive. Example Input: 560 400 218 280 10 25 88 10 8 13 5 1 9 13 10 6 199 333 40 2 75 90 218 280 999 99 1 10 0 0 0 0 Output: 50% 100% 12% 66% 1% 100% 1%
34,781
Consecutive Digits (CONDIG) As a recruiting ploy, Google once posted billboards in Harvard Square and in the Silicon Valley area just stating “{first 10-digit prime found in consecutive digits of e}.com”. In other words, find that 10-digit sequence and then connect to the web site — and find out that Google is trying to hire people who can solve a particular kind of problem. Not to be outdone, Gaggle (a loosy-goosy fuzzy logic search firm), has devised its own recruiting problem. Consider the base 7 expansion of a rational number. For example, the first few digits of the base 7 expansion of 1/5 10 = 0.12541... 7 , 33/4 10 = 11.15151... 7 , and 6/49 10 = 0.06000... 7 , From this expansion, find the digits in a particular range of positions to the right of the "decimal" point. Input The input file begins with a line containing a single integer specifying the number of problem sets in the file. Each problem set is specified by four base 10 numbers on a single line, n d b e, where n and d are the numerator and denominator of the rational number and 0 ≤ n ≤ 5,000 and 1 ≤ d ≤ 5,000. b and e are the beginning and ending positions for the desired range of digits, with 0 ≤ b,e ≤ 250 and 0 ≤ (e-b) ≤ 20. Note that 0 is the position immediately to the right of the decimal point. Output Each problem set will be numbered (beginning at one) and will generate a single line: Problem set k: n / d, base 7 digits b through e: result where k is replaced by the problem set number, result is your computed result, and the other values are the corresponding input values. Example Input: 4 1 5 0 0 6 49 1 3 33 4 2 7 511 977 122 126 Output: Problem set 1: 1 / 5, base 7 digits 0 through 0: 1 Problem set 2: 6 / 49, base 7 digits 1 through 3: 600 Problem set 3: 33 / 4, base 7 digits 2 through 7: 151515 Problem set 4: 511 / 977, base 7 digits 122 through 126: 12425
34,782
Painter (PAINTER) The local toy store sells small fingerpainting kits with between three and twelve 50ml bottles of paint, each a different color. The paints are bright and fun to work with, and have the useful property that if you mix X ml each of any three different colors, you get X ml of gray. (The paints are thick and "airy", almost like cake frosting, and when you mix them together the volume doesn't increase, the paint just gets more dense.) None of the individual colors are gray; the only way to get gray is by mixing exactly three distinct colors, but it doesn't matter which three. Your friend Emily is an elementary school teacher and every Friday she does a fingerpainting project with her class. Given the number of different colors needed, the amount of each color, and the amount of gray, your job is to calculate the number of kits needed for her class. Input The input consists of one or more test cases, followed by a line containing only zero that signals the end of the input. Each test case consists of a single line of five or more integers, which are separated by a space. The first integer N is the number of different colors (3 ≤ N ≤ 12). Following that are N different nonnegative integers, each at most 1,000, that specify the amount of each color needed. Last is a nonnegative integer G ≤ 1,000 that specifies the amount of gray needed. All quantities are in ml. Output For each test case, output the smallest number of fingerpainting kits sufficient to provide the required amounts of all the colors and gray. Note that all grays are considered equal, so in order to find the minimum number of kits for a test case you may need to make grays using different combinations of three distinct colors. Example Input: 3 40 95 21 0 7 25 60 400 250 0 60 0 500 4 90 95 75 95 10 4 90 95 75 95 11 5 0 0 0 0 0 333 0 Output: 2 8 2 3 4
34,783
Primary X-Subfactor Series (PRIMESUB) Let n be any positive integer. A factor of n is any number that divides evenly into n , without leaving a remainder. For example, 13 is a factor of 52, since 52/13 = 4. A subsequence of n is a number without a leading zero that can be obtained from n by discarding one or more of its digits. For example, 2, 13, 801, 882, and 1324 are subsequences of 8013824, but 214 is not (you can't rearrange digits), 8334 is not (you can't have more occurrences of a digit than appear in the original number), 8013824 is not (you must discard at least one digit), and 01 is not (you can't have a leading zero). A subfactor of n is an integer greater than 1 that is both a factor and a subsequence of n . 8013824 has subfactors 8, 13, and 14. Some numbers do not have a subfactor; for example, 6341 is not divisible by 6, 3, 4, 63, 64, 61, 34, 31, 41, 634, 631, 641, or 341. An x-subfactor series of n is a decreasing series of integers n 1 , ..., n k , in which (1) n = n 1 , (2) k ≥ 1, (3) for all 1 ≤ i < k , n i+1 is obtained from n i by first discarding the digits of a subfactor of n i , and then discarding leading zeros, if any, and (4) n k has no subfactor. The term "x-subfactor" is meant to suggest that a subfactor gets x'ed, or discarded, as you go from one number to the next. For example, 2004 has two distinct x-subfactor series, the second of which can be obtained in two distinct ways. The highlighted digits show the subfactor that was removed to produce the next number in the series. 2 004   4 200 4   20 0   0 200 4   2 00   0 The primary x-subfactor series has maximal length (the largest k possible, using the notation above). If there are two or more maximal-length series, then the one with the smallest second number is primary; if all maximal-length series have the same first and second numbers, then the one with the smallest third number is primary; and so on. Every positive integer has a unique primary x-subfactor series, although it may be possible to obtain it in more than one way, as is the case with 2004. Input The input consists of one or more positive integers, each less than one billion, without leading zeroes, and on a line by itself. Following is a line containing only "0" that signals the end of the input. Output For each positive integer, output its primary x-subfactor series using the exact format shown in the examples below. Example Input: 123456789 7 2004 6341 8013824 0 Output: 123456789 12345678 1245678 124568 12456 1245 124 12 1 7 2004 200 0 6341 8013824 13824 1324 132 12 1
34,784
Packing (PACK1) In the future the delivery services will be fully automated. A robot will come to your home to pick the boxes and leaves them in the central processing office where boxes for the same address are packed together. There is a machine that can pack two boxes into a one new box containing the privious two. If we want N boxes delivered to a certain city then this machine with N-1 operation will be able to consolidate them into single box. Each box has its size and a price for packing it equal to this size. The size of the box resulting from the machine packing two boxes together is simply equal to the sum of the two boxes that are packed together. Your goal is to find out the minimum price for packing N boxes into a single one using the packing machine. Input On the first line there will be one number N (1 < N < 5000001) – the number of boxes. N lines follow each line with one number representing the size of N-th box. The size will be less then 1 000 000. In 50% of the test cases the size will be less then 4000. Output Your program should output a single integer – the minum price that have to be paid for packing the N boxes into a single one using N-1 operations of the machine. Example Input: 4 1 1 1 1 Output: 8
34,785
Symmetric Order (SYMORD) In your job at Albatross Circus Management (yes, it's run by a bunch of clowns), you have just finished writing a program whose output is a list of names in nondescending order by length (so that each name is at least as long as the one preceding it). However, your boss does not like the way the output looks, and instead wants the output to appear more symmetric, with the shorter strings at the top and bottom and the longer strings in the middle. His rule is that each pair of names belongs on opposite ends of the list, and the first name in the pair is always in the top part of the list. In the first example set below, Bo and Pat are the first pair, Jean and Kevin the second pair, etc. Input The input consists of one or more sets of strings, followed by a final line containing only the value 0. Each set starts with a line containing an integer, n , which is the number of strings in the set, followed by n strings, one per line, sorted in nondescending order by length. None of the strings contain spaces. There is at least one and no more than 15 strings per set.  Each string is at most 25 characters long.  Output For each input set print "SET n" on a line, where n starts at 1, followed by the output set as shown in the sample output. Example Input: 7 Bo Pat Jean Kevin Claude William Marybeth 6 Jim Ben Zoe Joey Frederick Annabelle 5 John Bill Fran Stan Cece 0 Output: SET 1 Bo Jean Claude Marybeth William Kevin Pat SET 2 Jim Zoe Frederick Annabelle Joey Ben SET 3 John Fran Cece Stan Bill
34,786
Overflowing Bookshelf (BOOKSH) Agnes C. Mulligan is a fanatical bibliophile – she is constantly buying new books, and trying to find space for those books. In particular, she has a shelf for her “to be read” books, where she puts her newest books. When she decides to read one of these books, she removes it from the shelf, making space for more books. Sometimes, however, she buys a new book and puts it on the shelf, but because of limited space, this pushes one or more books off the shelf at the other end. She always adds books on the left side of the shelf, making books fall off the right side. Of course, she can remove a book from any location on the shelf when she wants to read one. Your task will be to write a simulator that will keep track of books added and removed from a shelf. At the end of the simulation, display the books remaining on the shelf, in order from left to right. Books in each simulation will be identified by a unique, positive integer, 0 < I ≤ 100. There are three types of events in the simulation: Add : A new book is pushed on the left end of the shelf, pushing other books to the right as needed. No book moves to the right unless it is pushed by an adjacent (touching) book on its left. Any book that is not entirely on the shelf falls off the right edge. No single book will ever be wider than the given shelf. No book that is currently on the shelf will be added again. Remove : If the book is on the shelf, then the book is removed from the shelf, leaving a hole. If the book isn't on the shelf, the operation is ignored. End : End the simulation for this case and print the contents of the shelf. Input The input file will contain data for one or more simulations. The end of the input is signalled by a line containing -1. Each simulation will begin with the integer width of the shelf, s , 5 ≤ s ≤ 100, followed by a series of add and remove events. An add event is a single line beginning with an upper case ' A ' followed by the book ID, followed by the integer width of the book, w , 0 < w ≤ s . A remove event is a single line beginning with an upper case ' R ' followed by the the book ID. Finally, the end event is a line containing only a single upper case ' E '. Each number in an event is preceded by a single blank. Output For each simulation case, print a single line containing a label (as shown in the output sample), followed by the list of IDs of books remaining on the shelf, in order from left to right. Input: 10 R 3 A 6 5 A 42 3 A 3 5 A 16 2 A 15 1 R 16 E 7 A 49 6 A 48 2 R 48 E 5 A 1 1 A 2 1 A 3 1 R 2 A 4 1 A 5 1 R 5 R 4 A 6 1 A 7 4 E -1 Output: PROBLEM 1: 15 3 PROBLEM 2: PROBLEM 3: 7 6
34,787
Flow Layout (FLOWLAY) A flow layout manager takes rectangular objects and places them in a rectangular window from left to right. If there isn't enough room in one row for an object, it is placed completely below all the objects in the first row at the left edge, where the order continues from left to right again. Given a set of rectangular dimensions and a maximum window width, you are to write a program that computes the dimensions of the final window after all the rectangles have been placed in it. For example, given a window that can be at most 35 units wide, and three rectangles with dimensions 10 x 5,  20 x 12, and 8 x 13, the flow layout manager would create a window that looked like the figures below after each rectangle was added. The final dimensions of the resulting window are 30 x 25, since the width of the first row is 10+20 = 30 and the combined height of the first and second rows is 12+13 = 25. Input The input consists of one or more sets of data, followed by a final line containing only the value 0. Each data set starts with a line containing an integer, m , 1 ≤ m ≤ 80, which is the maximum width of the resulting window. This is followed by at least one and at most 15 lines, each containing the dimensions of one rectangle, width first, then height. The end of the list of rectangles is signaled by the pair -1 -1, which is not counted as the dimensions of an actual rectangle. Each rectangle is between 1 and 80 units wide (inclusive) and between 1 and 100 units high (inclusive). Output For each input set print the width of the resulting window, followed by a space, then the lowercase letter " x ", followed by a space, then the height of the resulting window. Example Input: 35 10 5 20 12 8 13 -1 -1 25 10 5 20 13 3 12 -1 -1 15 5 17 5 17 5 17 7 9 7 20 2 10 -1 -1 0 Output: 30 x 25 23 x 18 15 x 47
34,788
Tree Grafting (GRAFT) Trees have many applications in computer science. Perhaps the most commonly used trees are rooted binary trees, but there are other types of rooted trees that may be useful as well. One example is ordered trees, in which the subtrees for any given node are ordered. The number of children of each node is variable, and there is no limit on the number. Formally, an ordered tree consists of a finite set of nodes T such that there is one node designated as the root, denoted root(T); the remaining nodes are partitioned into subsets T1, T2, ..., Tm, each of which is also a tree (subtrees). Also, define root(T1), ..., root(Tm) to be the children of root(T), with root(Ti) being the i-th child. The nodes root(T1), ..., root(Tm) are siblings. It is often more convenient to represent an ordered tree as a rooted binary tree, so that each node can be stored in the same amount of memory. The conversion is performed by the following steps: remove all edges from each node to its children; for each node, add an edge to its first child in T (if any) as the left child; for each node, add an edge to its next sibling in T (if any) as the right child. This is illustrated by the following: 0 0 / | \ / 1 2 3 ===> 1 / \ \ 4 5 2 / \ 4 3 \ 5 In most cases, the height of the tree (the number of edges in the longest root-to-leaf path) increases after the conversion. This is undesirable because the complexity of many algorithms on trees depends on its height. You are asked to write a program that computes the height of the tree before and after the conversion. Input The input is given by a number of lines giving the directions taken in a depth-first traversal of the trees. There is one line for each tree. For example, the tree above would give dudduduudu, meaning 0 down to 1, 1 up to 0, 0 down to 2, etc. The input is terminated by a line whose first character is #. You may assume that each tree has at least 2 and no more than 10000 nodes. Output For each tree, print the heights of the tree before and after the conversion specified above. Use the format: Tree t: h1 => h2 where t is the case number (starting from 1), h1 is the height of the tree before the conversion, and h2 is the height of the tree after the conversion. Example Input: dudduduudu ddddduuuuu dddduduuuu dddduuduuu # Output: Tree 1: 2 => 4 Tree 2: 5 => 5 Tree 3: 4 => 5 Tree 4: 4 => 4
34,789
Server Relocation (UPTIME) Michael has a powerful computer server that has hundreds of parallel processors and terabytes of main memory and disk space. Many important computations run continuously on this server, and power must be supplied to the server without interruption. Michael's server must be moved to accommodate new servers that have been purchased recently. Fortunately, Michael's server has two redundant power supplies---as long as at least one of the two power supplies is connected to an electrical outlet, the server can continue to run. When the server is connected to an electrical outlet, it can be moved to any location which is not further away from the outlet than the length of the cord used to connect to the outlet. Given which outlet Michael's server is plugged into initially and finally, and the locations of outlets in the server room, you should determine the smallest number of times you need to plug a cord into an electrical outlet in order to move the server while keeping the server running at all times. Note that, in the initial and final configuration, only one cord is connected to the power outlet. Input The first line of input is an integer giving the number of cases to follow. For each case, the first line is of the form OUTLETS OUTLET_INITIAL OUTLET_FINAL LENGTH1 LENGTH2 where OUTLETS is the number of outlets in the server room (2 <= OUTLETS <= 1000). OUTLET_INITIAL is the index (starting from 1) of the outlet the server is initially connected to. OUTLET_FINAL is the index (starting from 1) of the outlet the server is finally connected to. LENGTH1 and LENGTH2 are the positive lengths of the two power cords, with at most three digits of precision after the decimal point (0 < LENGTH1, LENGTH2 <= 30000). These are followed by OUTLETS lines giving the integer coordinates of the wall outlets, one per line, with the k-th line giving the location of the k-th outlet. All coordinates are specified as two integers (x- and y-coordinates) separated by a space, with absolute values at most 30000. You may assume that all coordinates are distinct, and that the initial outlet and the final outlet are different. Output For each case, print the minimum number of times you need to plug a cord into an electrical outlet in order to move the server to the final location while keeping the server running at all times. If this is not possible, print "Impossible". Example Input: 2 4 1 4 2.000 1.000 0 0 0 4 4 0 4 4 9 1 4 2.000 3.000 0 7 -6 2 -3 3 6 2 -6 -3 3 -3 6 -3 -3 -7 0 -7 Output: Impossible 8
34,790
Linear Pachinko (LINEARPA) This problem is inspired by Pachinko , a popular game in Japan. A traditional Pachinko machine is a cross between a vertical pinball machine and a slot machine. The player launches small steel balls to the top of the machine using a plunger as in pinball. A ball drops through a maze of pins that deflect the ball, and eventually the ball either exits at a hole in the bottom and is lost, or lands in one of many gates scattered throughout the machine which reward the player with more balls in varying amounts. Players who collect enough balls can trade them in for prizes. For the purposes of this problem, a linear Pachinko machine is a sequence of one or more of the following: holes (`` . "), floor tiles (`` _ "), walls (`` | "), and mountains (`` /\ "). A wall or mountain will never be adjacent to another wall or mountain. To play the game, a ball is dropped at random over some character within a machine. A ball dropped into a hole falls through. A ball dropped onto a floor tile stops immediately. A ball dropped onto the left side of a mountain rolls to the left across any number of consecutive floor tiles until it falls into a hole, falls off the left end of the machine, or stops by hitting a wall or mountain. A ball dropped onto the right side of a mountain behaves similarly. A ball dropped onto a wall behaves as if it were dropped onto the left or right side of a mountain, with a 50 % chance for each. If a ball is dropped at random over the machine, with all starting positions being equally likely, what is the probability that the ball will fall either through a hole or off an end? For example, consider the following machine, where the numbers just indicate character positions and are not part of the machine itself: 123456789 /\.|__/\. The probabilities that a ball will fall through a hole or off the end of the machine are as follows, by position: 1 = 100% , 2 = 100% , 3 = 100% , 4 = 50% , 5 = 0% , 6 = 0% , 7 = 0% , 8 = 100% , 9 = 100% . The combined probability for the whole machine is just the average, which is approximately 61.111% . Input The input consists of one or more linear Pachinko machines, each 1–79 characters long and on a line by itself, followed by a line containing only " # " that signals the end of the input. Output For each machine, compute as accurately as possible the probability that a ball will fall through a hole or off the end when dropped at random, then output a single line containing that percentage truncated to an integer by dropping any fractional part. Example Input: /\.|__/\. _._/\_|.__/\./\_ ... ___ ./\. _/\_ _|.|_|.|_|.|_ ____|_____ # Output: 61 53 100 0 100 50 53 10
34,791
Frugal Search (FRSEARCH) For this problem you will write a search engine that takes a query, searches a collection of words, and finds the lexicographically smallest word that matches the query (i.e., the matching word that would appear first in an English dictionary). A query is a sequence of one or more terms separated by single vertical bars (" | "). A term is one or more letters followed by zero or more signed letters. A signed letter is either + s ("positive" s ) or - s ("negative" s ), where s is a single letter. All letters are lowercase, and no letter will appear more than once within a term. A query will not contain spaces. A term matches a word if the word contains at least one of the unsigned letters, all of the positive letters, and none of the negative letters; a query matches a word if at least one of its terms matches the word. Input The input consists of one or more test cases followed by a line containing only " # " that signals the end of the input. Each test case consists of 1-100 words, each on a line by itself, followed by a line containing only " * " that marks the end of the word list, followed by one or more queries, each on a line by itself, followed by a line containing only " ** " that marks the end of the test case. Each word will consist of 1-20 lowercase letters. All words within a test case will be unique. Each query will be as defined above and will be 1-79 characters long. Output For each query, output a single line containing the lexicographically smallest word within that test case that matches the query, or the word NONE if there is no matching word. At the end of each test case, output a dollar sign on a line by itself. Example Input: elk cow bat * ea acm+e nm+o|jk+l ** debian slackware gentoo ubuntu suse fedora mepis * yts cab-e+n r-e|zjq|i+t|vs-p+e-u-c ** # Output: bat NONE elk $ gentoo ubuntu NONE $
34,792
Go Go Gorelians (GOGOGORE) The Gorelians travel through space using warp links. Travel through a warp link is instantaneous, but for safety reasons, an individual can only warp once every 10 hours. Also, the cost of creating a warp link increases directly with the linear distance between the link endpoints. The Gorelians, being the dominant force in the known universe, are often bored, so they frequently conquer new regions of space in the following manner. The initial invasion force finds a suitable planet and conquers it, establishing a Regional Gorelian Galactic Government, hereafter referred to as the RGGG, that will govern all Gorelian matters in this region of space. When the next planet is conquered, a single warp link is constructed between the new planet and the RGGG planet. Planets connected via warp links in this manner are said to be part of the Regional Gorelian Planetary Network, that is, the RGPN. As additional planets are conquered, each new planet is connected with a single warp link to the nearest planet already in the RGPN, thus keeping the cost of connecting new planets to the network to a minimum. If two or more planets are equidistant from the new planet, the new planet is connected to whichever of them was conquered first. This causes a problem however. Since planets are conquered in a more-or-less random fashion, after a while, the RGGG will probably not be in an ideal location. Some Gorelians needing to consult with the RGGG might only have to make one or two warps, but others might require dozens--very inconvenient when one considers the 10-hour waiting period between warps. So, once each Gorelian year, the RGGG analyzes the RGPN and relocates itself to an optimal location. The optimal location is defined as a planet that minimizes the maximum number of warps required to reach the RGGG from any planet in the RGPN. As it turns out, there is always exactly one or two such planets. When there are two, they are always directly adjacent via a warp link, and the RGGG divides itself evenly between the two planets. Your job is to write a program that finds the optimal planets for the RGGG. For the purposes of this problem, the region of space conquered by the Gorelians is defined as a cube that ranges from (0,0,0) to (1000,1000,1000). Input The input consists of a set of scenarios where the Gorelians conquer a region of space. Each scenario is independent. The first line of the scenario is an integer N that specifies the total number of planets conquered by the Gorelians. The next N lines of the input specify, in the order conquered, the ID s and coordinates of the conquered planets to be added to the RGPN, in the format ID   X   Y   Z . An ID is an integer from 1 to 1000. X , Y , and Z are integers from 0 to 1000. A single space separates the numbers. A value of N = 0 marks the end of the input. Output For each input scenario, output the ID s of the optimal planet or planets where the RGGG should relocate. For a single planet, simply output the planet ID . For two planets, output the planet ID s, smallest ID first, separated by a single space. Example Input: 5 1 0 0 0 2 0 0 1 3 0 0 2 4 0 0 3 5 0 0 4 5 1 0 0 0 2 1 1 0 3 3 2 0 4 2 1 0 5 3 0 0 10 21 71 76 4 97 32 5 69 70 33 19 35 3 79 81 8 31 91 17 67 52 31 48 75 48 90 14 4 41 73 2 21 83 74 41 69 26 32 30 24 0 Output: 3 2 4 31 97
34,793
Minimum Spanning Tree (MST) Find the minimum spanning tree of the graph. Input On the first line there will be two integers N - the number of nodes and M - the number of edges. (1 <= N <= 10000), (1 <= M <= 100000) M lines follow with three integers i j k on each line representing an edge between node i and j with weight k. The IDs of the nodes are between 1 and n inclusive. The weight of each edge will be <= 1000000. Output Single number representing the total weight of the minimum spanning tree on this graph. There will be only one possible MST. Example Input: 4 5 1 2 10 2 3 15 1 3 5 4 2 2 4 3 40 Output: 17
34,794
Connect (CONNECT2) Your task is to decide if a specified sequence of moves in the board game Connect ends with a winning move. In this version of the game, different board sizes may be specified. Pegs are placed on a board at integer coordinates in the range [ 0, N ]. Players Black and White use pegs of their own color. Black always starts and then alternates with White, placing a peg at one unoccupied position ( x , y ) . Black's endzones are where x equals 0 or N , and White's endzones are where y equals 0 or N . Neither player may place a peg in the other player's endzones. After each play, the latest position is connected by a segment to every position with a peg of the same color that is a chess knight's move away (2 away in one coordinate and 1 away in the other), provided that a new segment will touch no segment already added, except at an endpoint. Play stops after a winning move, which is when a player's segments complete a connected path between the player's endzones. For example, Figure 1 shows a board with N = 4 after the moves (0,2), (2,4), and (4,2). Figure 2 adds the next move (3,2). Figure 3a shows a poor next move of Black to (2,3). Figure 3b shows an alternate move for Black to (2,1) which would win the game. Figure 4 shows the board with N = 7 after Black wins in 11 moves: (0, 3), (6, 5), (3, 2), (5, 7), (7, 2), (4, 4), (5, 3), (5, 2), (4, 5), (4, 0), (2, 4) Input The input contains from 1 to 20 datasets followed by a line containing only two zeroes, ` 0 0 '. The first line of each dataset contains the maximum coordinate N (3 < N < 21) and the number of total moves, M (4 < M < 250) , with M odd, so Black will always be the last player. The dataset ends with one or more lines each containing two or more coordinate pairs, with a total of M coordinate pairs. All numbers on any line will be separated by blanks. All data will be legal. There will never be a winning move before the last move. Output The output contains one line for each data set: ` yes ' if the last move is a winning move and ` no ' otherwise. Example Input: 4 5 0 2 2 4 4 2 3 2 2 3 4 5 0 2 2 4 4 2 3 2 2 1 7 11 0 3 6 5 3 2 5 7 7 2 4 4 5 3 5 2 4 5 4 0 2 4 0 0 Output: no yes yes
34,795
Sum of Squares (SUMSQ) We are interested in how many different sequences of N non negative integers there are that have the sum of their squares less than S. Note that the sequence (1, 2) is different from the sequence (2, 1). Input The input consists of only one line with two integers N (0 < N < 30) and S ( S < 100 ). Output A single integer representing the number of different sequences that have the sum of their squares less than S. Example Input: 1 4 Output: 2
34,796
Fast Width (FASTW) When you want to get quick to some place in the city you don't often look for the shortest distance to there. Sometimes what is important is how width the street is. We will say that a route in the city had width is the width of the smallest street you will have to pass through. Now you are give the city network of streets and intersections and the width of each street and you are asked to provide the width of the widest path between intersection with number 1 and intersection with number N. Input On the first line of the input you will find two integers N (2 < N < 10000) the number of intersections in the city and M (1 < M < 100000) the number of streets in the city. On each of the next M lines you will get information about one street in the form of 3 integers I, J, W (1 < W < 65000) which will mean that intersections I and J are connected via street with width W. Output A single integer representing the width of the path between 1 and N with maximum width. If no path exists between 1 and N output 0 Example Input: 5 6 1 2 1 1 3 3 1 4 9 2 5 10 3 5 4 4 5 2 Output: 3
34,797
IOI07 Sails (SAILS) English Vietnamese A new pirate sailing ship is being built. The ship has N masts (poles) divided into unit sized segments – the height of a mast is equal to the number of its segments. Each mast is fitted with a number of sails and each sail exactly fits into one segment. Sails on one mast can be arbitrarily distributed among different segments, but each segment can be fitted with at most one sail. Different configurations of sails generate different amounts of thrust when exposed to the wind. Sails in front of other sails at the same height get less wind and contribute less thrust. For each sail we define its inefficiency as the total number of sails that are behind this sail and at the same height. Note that "in front of" and "behind" relate to the orientation of the ship: in the figure below, "in front of" means to the left, and "behind" means to the right. The total inefficiency of a configuration is the sum of the inefficiencies of all individual sails. This ship has 6 masts, of heights 3, 5, 4, 2, 4 and 3 from front (left side of image) to back. This distribution of sails gives a total inefficiency of 10. The individual inefficiency of each sail is written inside the sail. TASK Write a program that, given the height and the number of sails on each of the N masts, determines the smallest possible total inefficiency. INPUT The first line of input contains an integer N (2 ≤ N ≤ 100 000), the number of masts on the ship. Each of the following N lines contains two integers H and K (1 ≤ H ≤ 100 000, 1 ≤ K ≤ H), the height and the number of sails on the corresponding mast. Masts are given in order from the front to the back of the ship. OUTPUT Output should consist of a single integer, the smallest possible total inefficiency. Note: use a 64-bit integer type to calculate and output the result (long long in C/C++, int64 in Pascal). GRADING In test cases worth a total of 25 points, the total number of ways to arrange the sails will be at most 1 000 000. EXAMPLE input 6 3 2 5 3 4 1 2 1 4 3 3 2 output 10
34,798
IOI07 Training (TRAINING) English Vietnamese Mirko and Slavko are training hard for the annual tandem cycling marathon taking place in Croatia. They need to choose a route to train on. There are N cities and M roads in their country. Every road connects two cities and can be traversed in both directions. Exactly N−1 of those roads are paved, while the rest of the roads are unpaved trails. Fortunately, the network of roads was designed so that each pair of cities is connected by a path consisting of paved roads. In other words, the N cities and the N−1 paved roads form a tree structure. Additionally, each city is an endpoint for at most 10 roads total. A training route starts in some city, follows some roads and ends in the same city it started in. Mirko and Slavko like to see new places, so they made a rule never to go through the same city nor travel the same road twice. The training route may start in any city and does not need to visit every city. Riding in the back seat is easier, since the rider is shielded from the wind by the rider in the front. Because of this, Mirko and Slavko change seats in every city. To ensure that they get the same amount of training, they must choose a route with an even number of roads. Mirko and Slavko's competitors decided to block some of the unpaved roads, making it impossible for them to find a training route satisfying the above requirements. For each unpaved road there is a cost (a positive integer) associated with blocking the road. It is impossible to block paved roads. TASK Write a program that, given the description of the network of cities and roads, finds the smallest total cost needed to block the roads so that no training route exists satisfying the above requirements. INPUT The first line of input contains two integers N and M (2 ≤ N ≤ 1 000, N−1 ≤ M ≤ 5 000), the number of cities and the total number of roads. Each of the following M lines contains three integers A, B and C (1 ≤ A ≤ N, 1 ≤ B ≤ N, 0 ≤ C ≤ 10 000), describing one road. The numbers A and B are different and they represent the cities directly connected by the road. If C=0, the road is paved; otherwise, the road is unpaved and C represents the cost of blocking it. Each city is an endpoint for at most 10 roads. There will never be more than one road directly connecting a single pair of cities. OUTPUT Output should consist of a single integer, the smallest total cost as described in the problem statement. GRADING In test cases worth a total of 30 points, the paved roads will form a chain (that is, no city will be an endpoint for three or more paved roads). EXAMPLES input 5 8 2 1 0 3 2 0 4 3 0 5 4 0 1 3 2 3 5 2 2 4 5 2 5 1 output 5 input 9 14 1 2 0 1 3 0 2 3 14 2 6 15 3 4 0 3 5 0 3 6 12 3 7 13 4 6 10 5 6 0 5 7 0 5 8 0 6 9 11 8 9 0 output 48 The layout of the roads and cities in the first example. Paved roads are shown in bold. There are five possible routes for Mirko and Slavko. If the roads 1-3, 3-5 and 2-5 are blocked, then Mirko and Slavko cannot use any of the five routes. The cost of blocking these three roads is 5. It is also possible to block just two roads, 2-4 and 2-5, but this would result in a higher cost of 6.
34,799