task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Challenge Accepted (DCEPC11C) Aman and Arpit are bored of coding. There is no challenge in it anymore, they feel. Bear in mind that even the problems which would appear very difficult for most of you are trivial for them. With ICPC approaching, their teammate, Sameer, is worried by this development. So, to rekindle their interest in coding, he challenges them to a game. The game consists of an N × M grid (N rows, M columns). Some of the cells in the grid are occupied by coins. You can assume that all coins are identical. Sameer then gives them another grid of the same size, with a possibly different arrangement of coins. The objective is simple: the initial grid has to be transformed into the final grid, by moving coins. The following rules apply for coin movements: In one move, exactly one coin can be moved. A coin can move one cell up, down, left or right in one move, provided that the destination cell is empty. If the destination cell is occupied by another coin, then the current coin can jump over that particular coin to land in an empty cell. In fact, a coin can jump over any number of consecutive coins until it lands in an empty cell. It cannot jump over an empty cell. Irrespective of the number of coins it jumps over, it is still counted as one move. Whoever solves this in minimum number of moves will be the winner and will get a treat from Sameer. Since both Aman and Arpit really want to win, they immediately proceed to write code for the same. Can you help them predict the minimum number of moves in which the initial grid can be transformed into the final one? Input First line of input containts T, the number of test cases. First line of each test case contains 2 integers, N and M, separated by a single space. This is followed by 2 × N lines per test case. The first N lines represent the initial grid and the next N lines represent the final grid. Each character in the grid is either a ‘C’ or a ‘.’ ‘C’ means that there is a coin on that cell, and ‘.’ means that the cell is empty. Output For each test case, output a single line containing the minimum number of moves required. If it is not possible to transform the original grid into the final one, output ‘-1’ (without quotes) Constraints 1 ≤ T ≤ 10 1 ≤ N × M ≤ 20 Example Input: 2 1 5 .CC.. CC... 3 3 C.C .C. C.C ... CCC .CC Output: 1 3 Explanation: In the first test case, the coin to the right can jump over the coin to the left in 1 move.
33,400
Impossible Boss (DCEPC11I) Vaibhav Sir and Saikat Sir, after completing their graduation, got a job together at a store. Their boss at the store was Sidharth Sir, who was very strict and did not want anyone to have fun at the job. He gave Vaibhav and Saikat sir a very boring job of stacking columns of boxes in a row of size N. To make it a little interesting, both of them decided that whenever they need to add more boxes, they will choose st and en, such that 1 ≤ st ≤ en ≤ N, and place 1 box in column st, 2 boxes in column st+1 ... and (en - st + 1) boxes in column en. When Sidharth sir saw this, he decided to have some fun of his own, and asked them to count the number of boxes in all columns from st to en, and tell him the result. Now Vaibhav and Saikat sir have come to you for help to answer the queries of their boss, as they do not want to lose their jobs. Input The first line contains N, the number of columns and Q, the number of queries. The next Q lines can be of the following form – 0 st en, meaning Vaibhav and Saikat sir add boxes to the columns from st to en as described above. 1 st en, meaning Sidharth sir asks them to count the number of boxes in all columns from st to en. Output For all queries of type 2, output a line containing the answer to the query. Example Input: 5 6 0 2 4 1 1 5 0 1 5 0 3 5 1 1 5 1 3 5 Output: 6 27 23 Constraints 1 ≤ N, Q ≤ 100000
33,401
Boring Factorials (DCEPC11B) 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 close to P, and asks them to find N! modulo P. He asks T such queries. Input First line contains an integer T, the number of queries asked. Next T lines contains T queries of the form “N P”. (quotes for clarity) Output Output exactly T lines, containing N! modulo P. Example Input: 3 2 5 5 11 21 71 Output: 2 10 6 Constraints 1 ≤ T ≤ 1000 1 < P ≤ 2×10 9 1 ≤ N ≤ 2×10 9 Abs(N-P) ≤ 1000
33,402
Jailbreak (DCEPC11J) The great King Kapish has prisoned Pushap, for he loves the princess Padmavati. To make sure that Pushap and Padmavati never meet again, King Kapish has kept Pushap in his most mysterious of jail. This jail is built in a 2D rectangular grid fashion, containing M × N prison cells. The entrance gate for jail is at bottom left corner (0, 0). The mysteriousness of this jail comes from the fact that once a prisoner is taken from entrance gate (0, 0) to any prison cell, then that prisoner can escape only if he comes back to the entrance visiting the cells used on his way from entrance to his prison cell. Note that in the escape, it is not required for the prisoner to trace the exact path or visit all the cells used on his way up, rather the condition is to use/visit only those prison cells used on his way up. Additionally, when the prisoner is taken from entrance (0, 0) to a prison cell, they can fathom up to 2 cells in a single move/step in either upward direction or right direction. And when the prisoner is escaping, he can fathom up to 2 cells in a single move/step in either downward or left direction. King Kapish orders to jail prisoner Pushap in cell (M-1, N-1). You, being a common friend to Pushap and Padmavati, have to help Pushap escape the prison. Tell him the number of ways in which he can go up to cell (M-1, N-1) and then come back following the procedure described above. Please refer explanation part to know more. Input First line contains T, the number of test cases. Each test case contains 2 space separated integers, M and N. Output Output exactly T lines, each containing the required answer modulo 10 9 + 7. Constraints 1 ≤ T ≤ 10 1 < M, N ≤ 500 Example Input: 3 2 2 2 3 3 4 Output: 2 7 66 Explanation For (M, N) = (2, 3), one valid way to go up to prison cell and come back is as follows: Path taken for going from (0, 0) to (1, 2) = (0, 0) → (0, 1) → (0, 2) → (1, 2). Path taken for going from (1, 2) to (0, 0) = (1, 2) → (0, 2) → (0, 0).
33,403
Pabbu-pneumonia (CODPABBU) There is a biology experiment going in the biotech. lab of the "very prestigious" DTU. The students there are trying to study the reproduction patterns of a newly discovered species of virus pabbu-pneumoniae ;) These pabbu-pneumoniae virus reproduce in a rather strange and fascinating way. After adding "a" number of viruses to the petri dish on the first day of the experiment they make the following observations: On the second day, they found that the virus' number had been increased by "d". On the third day, they found that the new number of viruses in the dish was "r" times the number recorded on the second day. On the fourth day, they again found that the number had increased by "d" by that recorded on the third day... and so on... The pabbu-pneumoniae virus never cease to reproduce. For example, if d=1, r=4 and a=1..then the number of microbes recorded on each day would be: 1 2 8 9 36 37 148 149... Given 'a', 'd', 'r' and 'n', you have to find the number of microbes in the petri dish at the end of the n'th day. Since the numbers can be pretty large, you are required to print the answer modulo a number "m" ("m" will be supplied for each case) Input First line of input will have number 'T', the number of test cases. [T <= 2000] Each of the test cases will have 2 lines -: First line will have 3 space-separated numbers 'a','d'  and   'r' respectively. 2nd line will have 2 space-separated numbers 'n' and 'm' respectively. Output For each test case print the required answer in a separate line. NOTE - The value of a, d, r, n and m will be more than 0 and less than 10^8. Example Input: 1 1 2 3 4 5 Output: 1 Explanation: The sequence is - 1, 3, 9, 11, 33, 35, 105... The 4th term is 11 and 11 % 5 = 1
33,404
Easy Password (DCEPC11E) This is the year 2100. Pranjali ma’am due to her intelligence survived this far, by her “Secret Potion” to freeze her age. She keeps her lotion in a very secret vault which is electronic password protected. This is a very special system designed by our great Sameer sir, which don’t take any specific string as a password. Rather than it takes a “Tree”, yes you heard that right a “Tree” of numbers as a password. Your password should be exact to the tree both in structure and value to unlock the vault. Its high time and many hackers are trying to hack the system. So Pranjali ma’am was bit worried and wanted to change the password. Some of the new passwords are very vulnerable so Sameer sir told not to use them. You have to make the new password tree for Pranjali ma’am to keep her “Secret Potion” safe. You are given old password tree , and the one restricted password tree provided by Sameer sir. The structure and value of both might not be same as Sameer sir don’t know the exact password, he only know the current hacking pattern of the hackers. You have to make a new password tree with same structure as old password tree , with the nodes of old password tree permuted in some order and any new node should not be exactly equal in position and value to restricted password tree . The position of a node is defined by the sequence of moves (Left / Right) required to go down from the root to that node. If there are multiple answers, print the one whose difference is minimum from the old password tree . Calculating difference between trees: Diff = |sum((old[node[i]] - new[node[i]]) × 10 i )| where i is n-1 to 0. The ordering of nodes is based on level order traversal of trees. i.e. i will be n-1 for root node and so on. Input First line contains t, number of test cases. In each test case first line contain n and m, n is the number of nodes of old password tree and m is the number of nodes of restricted password tree . Next line contains n space separated numbers(value of nodes of old password tree ). Next n lines contains expression like A B, in ith line A and B is the left and right child of node with index i(0 based). If there is no right or left child of a node -1 will be provided in place of any index. Next line contains m space separated numbers (value of nodes of restricted password tree ). Then this tree is also described as the tree above. Output One integer. Minimum diff as per the above formula between old tree and new tree OR -1 if no such tree is possible. Constraints 1 ≤ T ≤ 50 0 ≤ node_value ≤ 9 1 ≤ n ≤ 18 Note: New tree can be same as old tree. If no such tree is possible print -1. All trees in the problem are Binary Trees. Example Input: 1 3 3 5 4 8 1 2 -1 -1 -1 -1 5 1 8 1 2 -1 -1 -1 -1 Output: 63 Explanation: According to the rule specified above the most feasible tree is rooted at node with value 4 and its left child being 8 and right child being 5. So the minimum diff is 63.
33,405
Dexters Trampoline (DTRAP) Dexter studies in Huber Elementary School, so does his arch rival Mandark. The school planned a fun trip to a carnival for N students. Everyone’s happy. Mandark has devised a plan to ruin the trip. He knows that there exist many groups within the students. Students of one group are friends with each other but not with any student of other groups. His plan is to instigate a fight among them. At the carnival, all students line up for time on a trampoline. Dexter learns about Mandark’s plan and knows that If two students that are not friends get on the trampoline at the same time, a fight will start. Suddenly his ‘lab alert’ buzzes. Deedee is trying to break into the lab again! Dexter has to get back home to defend his lab as soon as possible, but he can’t let Mandark ruin the trip. The trampoline can handle a total weight of W kgs. The students are getting impatient to get on the trampoline. To save time and to avoid a fight, Dexter decides that he will select the first batch of students to go on the trampoline in such a way that their total weight exactly equals W and that no two students are not friends. Your job is to tell him the number of ways he can do this. Dexter has the knowledge of only M pairs of friends. Input The first line contains T, the number test cases. T test cases follow. The first line of each test case contains three integers N, W and M. The next line contains N integers, The ith integer is the weight of the ith student (1 <= i <= N). The next M lines contain two integers, q and w; this tells that student q and student w are friends. Output For each test case, output a line containing a single integer, the number of ways Dexter can choose the first batch of students to get on the trampoline. Constraints 1 <= T <= 10 1 <= N <= 22 1 <= q, w <= N 0 <= M <= (N*(N+1))/2 1 <= W <= 1500 1 <= Weight of each student <= 60 Assume that the maximum number of students on the trampoline has no limit. Only the maximum weight on the trampoline has the limit W. Sample Input: 2 10 90 5 20 30 10 20 30 50 40 20 40 50 1 2 2 3 3 4 4 5 9 10 5 57 3 20 10 96 20 1 1 2 2 3 1 3 Output: 3 0 Explanation For first test case, the following three ways are possible. Using student number, (1, 2, 3, 5) (2, 3, 4, 5) (9, 10) For the second test case, there is no way for the total weight of selected students to be exactly W.
33,406
Anagrams (ANAGR) Two strings are said to be anagrams of each other if the letters of one string may be rearranged to make the other string.  In this problem you’ll be given two strings. Your job is to find if the two strings are anagrams of each other. If they are not anagrams then find the lexicographically smallest palindrome (in lowercase letters) that may be appended to the end of one of the two strings so that they become anagrams of each other. The lower and upper case letters are considered equivalent. The number of spaces  or any other punctuation is not important. Input The first line of the input contains a number T, the number of test cases. T test cases follow. Each test case consists of two lines, one string in each line. Output For each test case output a single line. Print ‘YES’ (without the quotes) if the two strings are anagrams of each other. If they are not, then print the lexicographically smallest string as discussed above. If no such string exists, then print ‘NO LUCK’ (without the quotes). Constraints 1<=T<=100 1<=length of the strings<=100 Sample INPUT: 4 Computer programmer mature germ romp crop Awaaay away internet web the terminator I’m rotten hater OUTPUT: YES aa NO LUCK YES
33,407
Kusac (KUSAC) Mirko has given up on the difficult coach job and switched to food tasting instead. Having skipped breakfast like a professional connoisseur, he is visiting a Croatian cured meat festival. The most renowned cook at the festival, Marijan Bajs, has prepared N equal sausages which need to be distributed to M tasters such that each taster gets a precisely equal amount. He will use his trusted knife to cut them into pieces. In order to elegantly divide the sausages, the number of cuts splitting individual sausages must be as small as possible. For instance, if there are two sausages and six tasters (the first test case below), it is sufficient to split each sausage into three equal parts, making a total of four cuts. On the other hand, if there are three sausages and four tasters (the second test case below), one possibility is cutting off three quarters of each sausage. Those larger parts will each go to one of the tasters, while the fourth taster will get the three smaller pieces (quarters) left over. Mirko wants to try the famous sausages, so he volunteered to help Bajs. Help them calculate the minimum total number of cuts needed to carry out the desired division. Input The first and only line of input contains two positive integers, N and M (1 ≤ N, M ≤ 100), the number of sausages and tasters, respectively. Output The first and only line of output must contain the required minimum number of cuts. Example Input: 2 6 Output: 4 Input: 3 4 Output: 3 Input: 6 2 Output: 0
33,408
Living with Courage (COURAGE) Courage (the cowardly dog) lives with his master Muriel and her husband Eustace in the city of Nowhere. Eustace is a farmer but not a very good one. One fine day Courage was taking a stroll in Eustace's cropless field when he found seeds of a magical tree. He sowed them in the field and the next morning n magical apple trees grew on the previously cropless field. The number of apples on the ith tree is apples[i] (0 ≤ i < n). The number of apples on a tree may change as sometimes courage eats some apples from a tree and sometimes apples grow instantly on the trees (because they are MAGICAL!!). Eustace wants to start a business of apples. So he frequently enquires Courage about the total number of apples present on a range of trees. A range of trees is denoted by two integers, l and r (0 ≤ l ≤ r < n) and includes the trees from l to r (both inclusive). Courage is very loyal to Muriel and wants to keep some apples for her. So whenever Eustace asks about the total number of apples on a range, he deliberately doesn't count the apples on a tree, s, such that l ≤ s ≤ r and MIN(apples[l], apples[l+1], apples[l+2] ... apples[r]) = apples[s]. In other words, while calculating the sum of apples on the trees in a range, Courage doesn't include the apples on the tree that has the minimum number of apples in that range. Input The first line contains n, the number of magical trees. The second line contains n non-negative integers that denote the array apples. The third line contains a non negative integer p, which is the number of events that take place. Now follow p lines. Each line will be of the form 'EAT x y' or 'GROW x y' or 'COUNT x y'. 'EAT x y' means that Courage ate x apples from the yth tree. (0 ≤ y < n) 'GROW x y' means that x apples grew magically on the yth tree (0 ≤ y < n). And 'COUNT l r' means that Eustace has told Courage to count the number of apples on the range of trees from l to r, both inclusive. Remember that the trees are indexed from 0. Output For each 'COUNT x y' event, output a single number that Courage tells to Eustace. Constraints 1 ≤ n ≤ 100000 1 ≤ p ≤ 100000 0 ≤ apples[i] ≤ 10 9 0 ≤ l ≤ r 0 ≤ y < n The number of apples on a tree never exceeds 10 9 . Sample: Input: 10 6 5 12 48 3 20 4 2 3 7 6 COUNT 2 4 COUNT 7 9 GROW 12 4 COUNT 2 4 EAT 6 9 COUNT 7 9 Output: 60 10 63 5 Explanation of the Sample: For 'COUNT 2 4', the sum of apples on trees 2,3 and 4 is 12+48+3=63. But as Courage doesn't include the apples on the tree with the minimum number of apples in the specified range (which in this case is the 4th tree), the number that he has to tell Eustace is 12+48=60. For 'COUNT 7 9', the sum of apples on trees 7,8 and 9 is 2+3+7=12. In this case the tree with the minimum number of apples in the range is the 7th tree. So Courage tell Eustace the number 3+7=10 'GROW 12 4' means that the 4th tree, which has 3 apples, grows 12 more apples on it. So the number of apples on the 4th tree becomes 15. For 'COUNT 2 4', the answer will be 48+15=63 'EAT 6 9' means that Courage eats 6 apples from the 9th tree. So the 9th tree now has 7-6=1 apple. For 'COUNT 7 9, the answer will be 2+3=5.
33,409
Clones (NCLNE) Trouble has befallen the ninja world (again!). As always, our hero Naruto has taken the responsibility to defend everyone from the evil forces. His signature attack is the cloning jutsu (i.e. cloning technique) in which he produces one clone of himself in one second. Each clone of Naruto can also perform the cloning technique. Naruto arrives alone at the battlefield at t = 1 second. At each time step, t = 1, 2, 3 ... n second, some of the Narutos will leave to start fighting the enemy and the rest will stay back and perform the cloning jutsu again. If a clone has left to fight the enemy he cannot come back to perform the jutsu. Also at t = n seconds all Narutos will go to fight with the enemy, i.e. no more cloning will take place on and after n seconds. Naruto is a very dedicated ninja so he won’t allow any of his clone to stay out of the fight. The commander of the ninja forces observes Naruto’s actions. He notes down the number of clones that went to fight the enemy at each time step (from t = 1 second until t = n second). However he is old and doubts if his observations are correct. He hires you, a ninja with sharp analytical skills, to check if his observations can be valid or not. Input The first line of the input contains t the number of test cases. The first line of each test case contains n, the time when all Naruto clones go to fight. In the second line of each test case there are n space separated integers that tell how many Naruto clones went to fight at successive seconds, starting from t = 1 second until t = n seconds; Output For each test case output either “Yes” or “No” (without quotes) in a single line. “Yes” if the commander’s observations were correct and “No” if they were wrong; Constraints 1 ≤ T ≤ 20 1 ≤ n ≤ 10 6 Each of the n integers will be less than or equal to 2 30 Example Input: 3 3 0 0 4 2 0 5 3 0 1 2 Output: Yes No Yes Explanation For the sample test case 2: 2 0 5 At t = 1 second, Naruto population is 1. According to the commander’s observations no Naruto leaves to fight at t = 1 (and all will perform the cloning jutsu), so the population will become 1 × 2 = 2. He observed that at t = 2 seconds, 5 Narutos went to fight. This is not possible as at t = 2 seconds the Naruto population is only 2. Therefore, the commander’s observations are incorrect.
33,410
Dilemma (GDIL) Garfield the cat likes candies A LOT. He always keeps a huge stock of it at his home. Today John, his owner, brought home three types of candies. He brought A pieces of Red candy, B pieces of Green candy and C pieces of Blue candy. Garfield is really happy. But the problem is that John won’t allow him to eat all of it at once. He will allow him to eat at most N candies. Garfield is very confused. His love for candies is clouding his judgement and he can’t make a decision on how to choose the N candies. Garfield is a dumb cat. So he asks you to find out in how many ways he can choose from the available type of candies so that he eats a total of N candies or less. Note: There is no difference between candies of the same color. Input The first line contains an integer t, the number of test cases. Each test case contains four space separated integers N, A, B, C. Output For each test case output a single line containing the number of ways Garfield can choose the N candies. Constraints 0 ≤ t ≤ 100 0 ≤ N, A, B, C ≤ 5000 ** No other constraints are applicable. Sample Input 3 2 1 2 3 1 1 1 1 2 1 0 1 Output 9 4 4 Explanation Explanation for the sample test case 1: For the test case 2 1 2 3, there is 1 piece of red candy, 2 pieces of green, and 3 pieces of blue. Garfield can eat at most 2 candies, so the possible combinations are (R,G,B): (0,0,0), (0,0,1), (0,0,2), (0,1,1), (1,0,1), (0,1,0), (0,2,0), (1,1,0), (1,0,0). Therefore 9 is the answer.
33,411
Running Median Again (RMID2) Danish has just solved the problem Running Median . The first line of the problem says "You will be given some integers in non-decreasing order". The problem asks you to report and remove the median of the list every time it is queried. Having solved this problem, Danish now begins to wonder how to solve the problem if the input is in any order (not necessarily non-decreasing order as mentioned above). Can you help him? Your task is to take as input a list of positive integers. Whenever -1 is given as input, you must output the median of the list, and remove it from the list. Take the smaller element as the median in case of even number of elements. Input The input contains several test caes. The first line contains an integer t, the number of test cases. Each test case has several lines, each containing an integer n (<=10^9) . If n is positive, add it to the list. n=-1 indicates a median query (there will be no median query if the list is empty). The test case is terminated by n=0. In each test case, there will be upto 10^5 integers to be added to the list, and upto 10^5 median queries. Output For each median query as described above, print the median on a new line. Example Input: 1 9 10 2 5 1 18 -1 -1 4 3 -1 8 7 -1 0 Output: 5 9 3 7
33,412
Real Numbers (REALNO) Find whether there exists a pair of real numbers whose sum is in range (1, 2) in an array consisting of real number in the range (0, 2) . If there exists such a pair print "found" else print "not found". (Double quotes only for clarity) Note : all intervals given above are open intervals. Input First line is the number of test cases t (t ≤ 6), then for each case number of real numbers in the array is given (n) then in the next line the real numbers are given. Output Print the required answer, i.e., " found " or " not found ". Constraints 1 ≤ n ≤ 3×10 5 Sample Input: 2 3 0.7 0.5 1.2 5 1.2 1.3 1.22 0.999 1.5 Output: found not found
33,413
Nanoworld (NANO) You're living in the future, way beyond the singularity and the exhaustion of ipv6, and you want to plan a fastest trip between your own planet and the planet of the your favourite restaurant. You have a map of one-directional nanobot ferry lines between the planets in your system. The map states the distance d ij between each (connected) pair of planets i and j , but due to the rapid technical evolution of this time, you estimate the travel time from i to j is d ij /t where t is the time at which you choose to depart from i . (It is impossible to travel at t=0). Input The first line contains T the number of test cases. The first line of each test case contains integers t0 , N , M where t0 is the time at which you start your trip. 0 ≤  t0  ≤ 10 9 N is the number of planets in your system, numbered 0...N-1. 0 < N  ≤ 2.5*10 5 M is the number of connections between planets. 0 < M  ≤ 2.5*10 5 The following M lines of each test case contain integers i , j , d where i is the source planet. 0 ≤ i < N j is the destination planet. 0 ≤ j < N d is the distance from i to j . 0 ≤ d  ≤ 10 9 Output The arrival time at planet N -1 when starting at planet 0 at time t0 , or "Impossible" (quotes for emphasis) if there is no possible route. Example Input: 2 0 5 5 0 2 2 2 3 3 3 4 4 0 1 5 1 4 6 0 2 1 1 1 0 Output: 4.91760625098 Impossible
33,414
On the side of the road (TAP2013A) On the side of the road, there are palm trees, there's a bar, there's shadow, there's something more. In this problem, we are particularly interested in the palm trees. Ana, Adan, Alan and Amanda organized a trip: while Ana and Adan where dealing with petty things like checking the car, preparing the luggage and finding a place to stay, Alan and Amanda dedicated themselves to the most important part: studying the views of palm trees to which they would have access to while on the road. The road they are now driving on is completely straight, and in this problem we will represent it by the Y = 0 line of the XY plane. On the side of the road with coordinates Y > 0 there are palm trees, which we will represent by different points of the XY plane with positive Y coordinate. Alan and Amanda have noticed that from each point on the road certain palm trees are visible, and in general these vary along the road. A palm tree is said to be visible from a point on the road if and only if the segment that joins both points does not go through any other palm tree. In the following figure the unfilled circles represent palm trees in the first sample input, whereas the filled ones represent some possible points on the road. From point p the palm trees that are visible are a , b and d , since palm tree c is hidden behind palm tree a . From point q the visible palm trees are a , c and d , since palm tree b is now hidden behind palm tree a . From point r all the palm trees are visible, and from point s only palm trees a and d are visible, since palm trees b and c are hidden behind palm tree d . While Ana and Adan take turns to drive the car, Alan and Amanda discuss the benefits of knowing how many visible quantities of palm trees there are. Given a set of palm trees, an integer number m is a visible quantity of palm trees if and only if there exists at least one point on the road (i.e. a point with coordinate Y = 0 ) from which exactly m palm trees are visible. In the example illustrated above, 2 , 3 and 4 are visible quantities of palm trees, as can be respectively testified by points s , p and r on the road. On the other hand, 0 and 1 are not visible quantities, because from every point of the road at least 2 palm trees are visible. Finally, no m > 4 is a visible quantity, since there are only 4 palm trees in total. Therefore, in this example there are 3 visible quantities of palm trees. (Note that if m is a visible quantity of palm trees, there could be more than one point on the road that testifies to this situation; in the previous example this is the case with points p and q for the visible quantity 3 , as well as with infinitely many other points along with r for visible quantity 4 .) Ana and Adan are getting tired. They want Alan and Amanda to let go of the palm trees and at least prepare some sandwiches. For that reason, you need to make a program to calculate how many different visible quantities of palm trees there are along the road. Input The first line contains an integer number N indicating the number of palm trees that there are on the side of the road ( 1 ≤ N  ≤  1000 ). Each of the following N lines describes a different palm tree using two integer numbers X and Y , representing the coordinates of said palm tree in the XY plane ( 1  ≤  X, Y  ≤  10 5 ). There are no two palm trees that share the same position. Output Print a single line containing an integer number representing the number of visible quantities of palm trees that there are along the road. Example 1 Input: 4 2 1 3 1 3 2 3 3 Output: 3 Example 2 Input: 7 2 1 3 1 4 1 1 2 3 2 5 2 3 3 Output: 4
33,415
Little Red-Cap (TAP2013C) Once upon a time there was a very joyous girl who was called Little Red-Cap because she always wore a red riding cap. Red-Cap enjoyed a lot her strolls in the woods, during which she collected berries in her small basket to offer them to her grandmother, who was known to prepare the most delicious pies of all the region. However, Red-Cap definitely did not enjoy the perils of the woods, and in particular the Big Bad Wolf who was always hungry and prying. One day, Red-Cap decides to go from her home to that of her grandmother, collecting berries on the way and trying to make her journey in the safest possible way. Red-Cap's house is in a clearing at the westernmost point of the woods, her grandmother's house is in another clearing at the easternmost point, and inside the woods between them there are some other clearings containing berry trees. The woods are very dense, so the only way to go through them is using the pathways between the clearings, which fortunately Red-Cap knows very well. In order not to get lost, Red-Cap always moves through pathways that take her to a point strictly to the east of the point where she is. In order not to be caught by the wolf Red-Cap finds it imperative to avoid an ambush, and for that reason she always has in mind the number of different paths that take her from her current position to her grandmother's home. A path in the woods is a sequence of clearings ordered from west to east, such that each clearing is connected with the next by a pathway. A path to the house of Red-Cap's grandmother is simply a path whose last clearing contains said house. For each clearing, its level of alternatives is the number of paths that go from it to Red-Cap's grandmother's house. In turn, for each path its level of alternatives is the sum of the levels of alternatives of all the clearings that make up that path. In order not to be captured by the wolf, Red-Cap wants to find the path with a maximum level of alternatives, starting at her house and ending at her grandmother's house. Can you help her? Input The first line contains two integer numbers N and S which respectively indicate the number of clearings and the number of pathways in the woods ( 3 ≤ N  ≤  3 × 10 4 and 2  ≤  S  ≤  10 5 ). The clearings are identified by different integer numbers between 1 and N , and are ordered from west to east, so that if 1  ≤  i < j  ≤  N then clearing i is to the west of clearing j . Red-Cap's house is in clearing 1 , whereas her grandmother's house is in clearing N . Each of the following S lines describes a pathway using two integer numbers I and J , which indicate that there is a pathway between clearing I and clearing J ( 1  ≤  I < J  ≤  N ). There is at least one path from Red-Cap's house to her grandmother's house, and the maximum level of alternatives among the set of all such paths is no greater than 10 18 . Output Print a single line containing an integer number, representing the maximum level of alternatives for a path from Red-Cap's house to her grandmother's house. Example 1 Input: 3 2 1 2 2 3 Output: 3 Example 2 Input: 4 6 1 2 2 3 3 4 1 2 2 3 3 4 Output: 15 Example 3 Input: 9 9 1 3 2 3 3 4 4 5 1 5 3 4 3 9 7 8 4 9 Output: 8
33,416
Watching the game (TAP2013D) In the kingdom of Nlogonia there is a lake known as the " Big O " because of its perfectly round shape. On the side of this lake there are N houses, each of them a distance of one nlogonic unit apart from its neighbors. The houses are numbered from 1 to N in clockwise order, as can be seen in the following figure for N = 8 . In this way, if i < j the distance in clockwise order from house i to house j is j-i , whereas the corresponding distance in counterclockwise order is N - j + i . Note that the distance from a house to itself is N in both directions. It is well known that the people of Nlogonia are avid football fans, so when a family moves to a house on the side of the lake it is very important for them to know who are their closest neighbors that follow the same team as they do. This is not always easy, since there may be many houses around the lake, many different football teams in Nlogonia, and a lot of moving around. Given a sequence of M movings, people who live on the shore of the lake want to welcome each new family arriving by telling them the distance from their new home to the closest houses that follow the same team as they do, both in clockwise and counterclockwise order. Note that if there is no other house on the shore of the lake whose family follows the same team as the newly arrived, said distance shall be N in both directions, as the closest house would in fact be the same house involved in the moving. Do you want to take part in the welcoming committee? In Nlogonia there are F football teams, identified by different integer numbers from 0 to F-1 . Because we don't want you to waste any time going from door to door asking which team is followed in each house, we will assume that initially the family living in house number i is a fan of team number e i , being this number generated in pseudo-random fashion by the recursive formula e 1 = A      and      e i = (B × e i-1  + C) mod F      for      i = 2, 3, ..., N where A , B and C are constants and the expression x mod y represents the remainder of the integer division of x by y .   Input The first line contains two integer numbers N and F , respectively indicating the number of houses around the lake and the number of football teams in Nlogonia ( 3 ≤ N  ≤  10 5 and 1  ≤  F  ≤  10 6 ). The second line contains three integer numbers A , B and C , which determine which team is followed by the families initially living around the lake as is described in the problem statement ( 0  ≤  A, B, C < F ). The third line contains a single integer number M , representing the number of movings that will be happening ( 1  ≤  M  ≤  10 5 ). Each of the following M lines describes a moving using two integer numbers I and E , meaning that a family following team E is moving to house number I ( 1  ≤  I  ≤  N and 0  ≤  E < F ). The movings appear in the order that they occur, and should be taken into account by the committee for further welcomings.   Output Print M lines, the i -th of them indicating the result of the i -th moving described in the input. Each line should contain two integer numbers d ccw and d cw , representing the distances in nlogonic units from the house involved in the moving to the first house whose family follows the same team, in counterclockwise and clockwise order respectively.   Example Input: 5 10 1 1 1 6 1 1 2 2 3 1 4 2 5 1 3 1 Output: 5 5 5 5 2 3 2 3 2 1 2 2
33,417
Escaping from escaping (TAP2013E) A communications protocol is a set of rules designed to transfer information in a communications system. Elisa's job is to write programs that implement parts of said protocols. It is often necessary for this to transfer sequences of fields, and in order to know where a field ends and the next one begins it is customary to insert a separator between each pair of consecutive fields. Using a simple separator such as a space, a comma or a semicolon is inconvenient because sometimes the fields to be transferred contain these same characters. The standard solution in these cases is to insert an " escaping " character just before every appearance of a separator inside a field, so that it can be thus distinguished from a real separator. Elisa thinks this solution will increase a lot the length of the data to be transmitted, so she has decided to use a separator that is complex enough for it to never appear inside the data. In this way she hopes to escape the inefficient alternative of escaping separators. To choose the ideal separator, Elisa has compiled a log , which is nothing else than a long string of characters that is representative of the data that her protocol needs to manage. After thinking about the problem for a while, Elisa reached the conclusion that any non-empty string of characters that does not appear inside the log would be an acceptable separator for use within her protocol. But because she is interested in minimizing the length of the data to be transmitted, she would like to know the minimal length that an acceptable separator can have. She immediately wrote a program to calculate this length, and is now testing it for the particular case in which both the log and the acceptable separators only contain binary digits ( ' 0 ' and ' 1 ' ). Can you anticipate the results? Input The first line contains an integer number T , the number of test cases ( 1 ≤ T ≤ 200 ). Each of the following T lines contains a log, which is a non-empty string of at most 10 5 binary digits. Output For each test case, print a single line containing an integer number representing the minimal length of an acceptable separator for the given log. Example Input: 3 011101001 100010110011101 11111 Output: 3 4 1
33,418
Flowers of Babylon (TAP2013F) In Babylon grow some plants with flowers that are very much appreciated among the inhabitants. Florencio is such an inhabitant of Babylon who has a garden with N plants of these species, and he wants to collect some of their flowers. Because Florencio is quite lazy he does not want to go through a lot of effort to collect the flowers. Therefore, he has decided to walk to some point in his garden, and then with a circular movement of his scythe he shall cut a good amount of plants to later collect their flowers. Florencio is very skillful using the scythe so he will cover with it a perfect circle centered wherever he is standing, which will allow him to cut all the plants lying within this circle, including its border. The higher Florencio has to lift his scythe, the greater the radius of the corresponding circle he will cover with it. Florencio wants to cut at least P plants, but his laziness is such that he wants to do so lifting his scythe as little as possible. Florencio has managed to get his hands on a satellite image of his garden where all of his plants appear, and he has furthermore managed to get someone to convert this image to a list where each plant is represented by its coordinates in an XY plane. Now he is sitting outside, his scythe in hand, waiting for your team to tell him the minimum radius of a circle that encloses at least P plants. Input The first line contains a single integer number T , the number of test cases ( 1 ≤ T ≤ 100 ). For each test case, the first line contains two integer numbers N and P , which respectively represent the number of plants that there are in the garden and the minimum number of plants that Florencio wants to cut ( 1 ≤ P  ≤  N  ≤  500 ). Each of the following N lines describes a different plant using two integer numbers X and Y , representing the coordinates of that plant in the XY plane ( 1  ≤  X, Y  ≤  10 5 ). No two plants sit at the same position. Output For each test case, print a line containing a single rational number representing the minimum radius of a circle enclosing at least P plants. You should print the result using exactly 4 digits after the decimal mark, rounding if necessary (there will be no rounding ties). Example Input: 2 3 2 10000 10000 10000 9999 9999 10000 2 1 1 1 10000 10000 Output: 0.5000 0.0000
33,419
War (TAP2013G) War, an event worthy only of appearance in literature, movies or perhaps programming contests, has reached the Nlogonian empire, which is facing the neighboring empire of Quadradonia. War protocols agreed upon by both parties indicate that the war will be waged in successive battles, in each of which a different soldier from each empire will face one another, so that each soldier will take part in exactly one battle. The empire that wins more battles will then win the war. Each empire has an army formed by S soldiers, and each soldier has a certain combat skill. In each battle between two soldiers, the one with greatest combat skill wins the battle. If both soldiers have the same combat skills, the battle is declared a draw and technically no side claims victory. The spies of Nlogonia have intercepted secret information concerning the combat skill of each soldier of Quadradonia's army, so Nlogonia's queen requires your assistance in order to calculate the maximum number of battles that can be won during the war if her soldiers are sent in the appropriate order. Input The first line contains an integer number S representing the number of soldiers in each army ( 1 ≤ S  ≤  10 5 ). The second line contains S integer numbers Q i representing the combat skills of the different soldiers of Quadradonia's army, in the order in which the battles shall take place ( 1  ≤  Q i   ≤  10 9 for i = 1, ..., S ). The third line contains S integer numbers N i representing the combat skills of the different soldiers in Nlogonia's army, in an arbitrary order ( 1  ≤  N i   ≤  10 9  for i = 1, ..., S ). Output Print a line containing a single integer number representing the maximum number of battles that Nlogonia can win during the war. Example 1 Input: 3 2 1 1000000000 1 1 2 Output: 1 Example 2 Input: 4 6 3 1 4 2 7 4 3 Output: 3
33,420
Horace and his primes (TAP2013H) Horace likes to play writing natural numbers in the blackboard in his bedroom. One of his favourite games consists in first writing a number n , then the sum of all the different prime numbers that divide n , and so on until the number written on the board becomes a prime number. For example, if Horace begins writing the number n = 90 , because 90 = 2 × 3 2  × 5 the next number to be written will be 2 + 3 + 5 = 10 ; then, as  10 = 2 × 5 Horace will write the number 2 + 5 = 7 ; finally, because 7 is a prime number the game will end here. Formally, in this game each natural number n >= 2 defines a sequence whose first element is n, and each new element is the sum of all the prime numbers that divide the previous element in the sequence. The order of the game is the position of the first prime number in the sequence, and coincides with the total number of numbers written on the blackboard one the game has ended. In the example from the previous paragraph, with n = 90 the order of the game is K = 3, because the numbers that are written will be 90, 10 and 7. Now, not all games are equally entertaining to Horace, and in this case he prefers to begin by writing a number n such that the order of the corresponding game is a particular value K. Horace would like to know how many different values of n between A and B inclusive satisfy this condition, but because he does not know how to code he needs someone to do this calculation for him. Can you help him? INPUT The first line contains an integer P which indicates the number of questions Horace wants to ask you (1 <= P <= 10^5). Each of the next P lines describes a question using three integer numbers A, B and K, which mean that Horace would like to know how many different values of n satisfy that A <= n <= B and the order of the game beggining with n is K (2 <= A <= B <= 10^6 and 1 <= K <= 10^6). OUTPUT You should print P lines, each one containing an integer number with the answer to one of the questions made by Horace, in the order in which they appear in the input. Formally, in this game each natural number n ≥ 2 defines a sequence whose first element is n , and each new element is the sum of all the prime numbers that divide the previous element in the sequence. The order of the game is the position of the first prime number in the sequence, and coincides with the total amount of numbers written on the blackboard once the game has ended. In the example from the previous paragraph, with n = 90 the order of the game is K = 3 , because the numbers that are written will be 90 , 10 and 7 . Now, not all games are equally entertaining to Horace, and in this case he prefers to begin by writing a number n such that the order of the corresponding game is a particular value K . Horace would like to know how many different values of n between A and B inclusive satisfy this condition, but because he does not know how to code he needs someone to do this calculation for him. Can you help him? Input The first line contains an integer P which indicates the number of questions Horace wants to ask you ( 1  ≤  P ≤ 10 5 ). Each of the next P lines describes a question using three integer numbers A , B and K , which mean that Horace would like to know how many different values of n satisfy that A  ≤  n  ≤  B and the order of the game beginning with n is K ( 2  ≤  A  ≤  B  ≤  10 6 and 1  ≤  K  ≤  10 6 ). Output You should print P lines, each one containing an integer number with the answer to one of the questions made by Horace, in the order in which they appear in the input. Example 1 Input: 1 90 90 3 Output: 1 Example 2 Input: 5 2 9 1 2 9 2 800 810 4 999999 1000000 2 100000 1000000 1000000 Output: 4 4 5 2 0
33,421
Treasure Island (TAP2013I) Finding the treasures hidden centuries ago by the pirates of the Caribbean islands is no easy task, but even more difficult is living to tell the story. This is because, as everybody knows, pirates had supernatural powers which they used to curse the person who took their treasure unauthorized. A very common curse among the most powerful of pirates, and for which it is always a good idea to be prepared, is known today as the deadly mist . Whenever a pirate's treasure is found, this curse will make a poisonous mist lift from the ground until the whole island gets covered by it. Any living creature that is touched by the mist will die instantly, something especially undesirable for those who have just found a treasure. The only way to save yourself is then to return to your boat, always going through areas that have not yet been covered by the mist, and thus flee with that part of the treasure that may have been rescued. In this problem we are interested in knowing what's the maximum amount of time that one can take to collect the treasure in such a way so as to be able to return to the boat alive. To simplify the problem, we will consider that an island can be represented by a grid with R rows and C columns, in which the cell in the i -th row and the j -th column has height H ij  above sea level. Furthermore, we will assume that the treasure is always hidden in the cell in row 1 and column 1 , because this is the one furthest away from the only place where the boat can set anchor, which is the cell in row R and column C . The deadly mist appears at sea level at the very same instant that the treasure is found, and then rises on all the island at a rate of one unit of height per second, so that after t seconds one cannot be in any cell of height less or equal to t . In order to return to the boat, you may go from one cell to another only if they share a side, so that if you are on a given cell you can only move horizontally to the cell before or after it in the same row, or vertically to the cell before or after it in the same column, but you cannot move diagonally or cross the boundaries of the island. Each such movement from one cell to another takes exactly one second. Input The first line contains two integer numbers R and C , respectively the number of rows and columns of the grid that represents the island, which consists of at least two cells ( 1 ≤ R, C ≤  500 and R×C ≥ 2 ). Each of the following R lines contains C values. In the i -th of these R lines, the j -th value is an integer H ij  representing the height of the cell at row i and column j ( 1 ≤  H ij   ≤  10 6 for i = 1, ..., R and j = 1, ..., C ). Output Print a single line containing an integer number representing the maximum amount of time in seconds that one can take to collect the treasure, so as to be able to return to the boat without being reached by the deadly mist. Print the number -1 if it is impossible to return to the boat even if one starts the way back as soon as the treasure is discovered. Example 1 Input: 3 3 2 3 4 3 4 5 4 5 6 Output: 1 Example 2 Input: 3 3 1 2 3 2 2 3 2 4 5 Output: -1 Example 3 Input: 3 2 1000000 1000000 1000000 1000000 1000000 314 Output: 310
33,422
Game of stones (TAP2013J) Jaimito loves to play with the N identical stones that he was given for his birthday, piling them to form mountains of various sizes. His happiness would be perfect if her mother, Jimena, did not constantly remind him that at the end of the day comes the Time to Arrange the Piles (TAP). It is then that Jaimito must destroy his mountains of stones, which he had piled up with so much effort. Because Jimena knows how much Jaimito is bothered by the TAP, she suggests to play a game with him in order to make this task more fun. Jaimito and his mother take turns to play, with Jaimito starting because he is the youngest. Initially there are one or more mountains, each one of them composed of a certain number of stones. In his turn each player chooses a mountain with more than one stone and divides it to form two mountains, not necessarily of the same size. The game continues in this way until one of the players cannot make a valid move, at which point this player is declared the looser, the other player being the winner. Jaimito is a very smart kid, and he has realized that he can distribute the N stones to form the mountains in a strategic way, so as to be certain that when they begin to play with these mountains he will undoubtedly win during the TAP. Because of the way the game works, Jaimito will not consider that two initial arrangements of the stones are different if they only change in the order in which the mountains are given. This means that in order for him to consider two initial distributions to be different, these need to have a different number of mountains or, if the number of mountains is the same, then the stones must be distributed in a different way among the mountains. For example, if Jaimito has N = 4 stones, there are five ways in which he can initially distribute them in mountains: four mountains of one stone each; two mountains of one stone each, and another mountain with two stones; one mountain of one stone, and another mountain with three stones; two mountains of two stones each; and, lastly, a single mountain with all four stones. Because Jaimito does not want his mother to realize that he is cheating, he wants to change the initial distribution of the N stones every day. He is convinced that there are many different ways to initially arrange the stones that will guarantee him the victory, but he does not know how many exactly. For example, in the case with N = 4 stones Jaimito only has two possible ways to choose from: a single mountain with four stones, or two mountains of one stone each and another mountain with two stones. Your team's task in this problem is to help Jaimito count the number of different ways in which he can distribute his N stones in mountains in such a way that his victory is certain when playing against Jimena. In this way, Jaimito will rest assured knowing how many days he can win without his mother doubting of his good intentions. Input The first line contains an integer number T , the number of test cases ( 1 ≤ T ≤ 200 ). Each of the following T lines contains an integer number N , representing the number of stones Jaimito has ( 2 ≤ N  ≤  1000 ). Output For each test case print a line containing a single integer number representing the number of different ways in which the N stones can initially be arranged in mountains so as to guarantee that Jaimito will win the game against Jimena. Because the answer can be a very large number, you only have to print the remainder of its division by 10 9 +7 . Example Input: 2 4 239 Output: 2 465766207
33,423
Sir and The ICC Ratings (ICC) Everyone knows Sir Jadeja can alone blow the opposition away. Sir has dominated the ICC Rankings as well. One day he was going through his career rating graph on Cricinfo.com and noticed the peaks in the graph. He found these graphs interesting and decides to create many hypothetical graphs. In all his graphs, at any time  the slope of the graph is either 45 o (increasing) or -45 o (decreasing) only and takes non-negative integral values only. Since the graphs are hypothetical he starts the graph at rating 0 and end it at 0 too. In between the end points the total time covered is 2N (horizontal axis) units and there are a total of K peaks. He wants to calculate the total number of different graphs for a given N and K. Since the answer could be very large, print it modulo 10 9 +7. You too are supposed to be good at Maths, so please help Sir solve the problem. Input First Line denotes the number of test cases T (1 ≤ T ≤ 1000000). Each test case consists of two numbers, N and K. 1 ≤ K ≤ N ≤ 1000. Output Total number of such graphs modulo 1000000007. Example Input: 1 5 2 Output: 10
33,424
Playing with isosceles triangle (TRIISO) Naruto was always alone as a kid. He used to get bored a lot and always tried different things for fun. Once he got fascinated by isosceles triangles and developed a game. He will choose a integer value S to be length of the equal sides of the isosceles triangle. Now if it is possible that he can form any triangle which has a third side of even length as well a height of integral value with the third side as base then he becomes happy. Given S determine if Naruto will be happy. Input First line contains T, the number of test cases, T ≤ 10000. The next T lines each contain a integer value S < 1000000. Output For each of T test cases output YES if Naruto will be happy and NO otherwise. Example Input: 2 5 8 Output: YES NO Explanation: In 1st case for S = 5, the third side can be 6 and height can be 4. In 2nd case for S = 8, no such combination is possible.
33,425
Game of stones II (GOSTONES) [An easier version of this problem was used in the Argentinian Programming Tournament of 2013. You may want to try it before proceeding with this one: http://www.spoj.com/problems/TAP2013J/ ] Jaimito loves to play with the N identical stones that he was given for his birthday, piling them to form mountains of various sizes. His happiness would be perfect if her mother, Jimena, did not constantly remind him that at the end of the day comes the Time to Arrange the Piles (TAP). It is then that Jaimito must destroy his mountains of stones, which he had piled up with so much effort. Because Jimena knows how much Jaimito is bothered by the TAP, she suggests to play a game with him in order to make this task more fun. Jaimito and his mother take turns to play, with Jaimito starting because he is the youngest. Initially there are one or more mountains, each one of them composed of a certain number of stones. In his turn each player chooses a mountain with more than one stone and divides it to form two mountains, not necessarily of the same size. The game continues in this way until one of the players cannot make a valid move, at which point this player is declared the looser, the other player being the winner. Jaimito is a very smart kid, and he has realized that he can distribute the N stones to form the mountains in a strategic way, so as to be certain that when they begin to play with these mountains he will undoubtedly win during the TAP. Because of the way the game works, Jaimito will not consider that two initial arrangements of the stones are different if they only change in the order in which the mountains are given. This means that in order for him to consider two initial distributions to be different, these need to have a different number of mountains or, if the number of mountains is the same, then the stones must be distributed in a different way among the mountains. For example, if Jaimito has N = 4 stones, there are five ways in which he can initially distribute them in mountains: four mountains of one stone each; two mountains of one stone each, and another mountain with two stones; one mountain of one stone, and another mountain with three stones; two mountains of two stones each; and, lastly, a single mountain with all four stones. Because Jaimito does not want his mother to realize that he is cheating, he wants to change the initial distribution of the N stones every day. He is convinced that there are many different ways to initially arrange the stones that will guarantee him the victory, but he does not know how many exactly. For example, in the case with N = 4 stones Jaimito only has two possible ways to choose from: a single mountain with four stones, or two mountains of one stone each and another mountain with two stones. Your team's task in this problem is to help Jaimito count the number of different ways in which he can distribute his N stones in mountains in such a way that his victory is certain when playing against Jimena. In this way, Jaimito will rest assured knowing how many days he can win without his mother doubting of his good intentions. Input The first line contains an integer number T , the number of test cases ( 1 ≤  T ≤  10 4 ). Each of the following T lines contains an integer number N , representing the number of stones Jaimito has ( 2 ≤ N ≤ 10 5 ). Output For each test case print a line containing a single integer number representing the number of different ways in which the N stones can initially be arranged in mountains so as to guarantee that Jaimito will win the game against Jimena. Because the answer can be a very large number, you only have to print the remainder of its division by 10 9 +7 . Example Input: 2 4 12345 Output: 2 483042273
33,426
Help Vishnu with his points (RUMMY) Vishnu is very fond of Rummy. Rummy is a game played with standard set of cards. Each deck has 52 cards, 4 suits with 13 ranks each. In Rummy, however, multiple decks can be used in a single game. In our problem we ignore card suits and are only looking at ranks. Those are as follows (from lowest to highest): A, 2, 3 ... 10, J, Q, K, (A). Ace is a special card that can be treated both as lowest (before 2) and highest rank (after K). Rummy has different variants, our is as follows. Each player has a hand of exactly 13 cards. Cards are being discarded from a hand by constructing sets. Each card can belong to at most one set. There are two types of valid sets: Exactly three cards of the same rank, for example (2, 2, 2) or (Q, Q, Q). Sequence of at least three cards. Sequence is a set of consecutive ranked cards, with at most one card for each rank. Some examples: (2, 3, 4, 5), (Q, K, A), (A, 2, 3), (9, 10, J, Q). Note that set (K, A, 2) would not be a valid sequence, since a given Ace card can only have one of the two ranks, not both. In addition one of the ranks is chosen to be treated as Jokers, denoted as JK. When constructing sequences, jokers can be used to substitute any rank. For example: (2, JK, 4), (J, Q, JK, A). There can be more than one joker in a single hand. Each of them can be treated as a different rank to be used in a single sequence. Examples: (7, JK, 9, JK, J), (JK, 4, JK, JK, 7). Jokers don't alter the way type (1) sets are build. For example (5, 5, JK) is invalid, but (JK, JK, JK) still can be formed. Each card has a number of points assigned to it. Ranks 2 to 10 have points equal to their number. A, J, Q, K are 10 points each and Jokers are 0 points. Number of points on a hand is a sum of this hands cards points. The goal of the game is to have minimum number of points after removing some number of sets (possibly none). Help Vishnu find the optimal score for a given hand. Input Single integer T (1 ≤ T ≤ 20) on the first line, the number of test cases. The next T lines contain 14 numbers each, all positive integers not bigger than 13. First 13 describe cards in Vishnu hand and the 14th is the rank chosen to be Jokers. Integers 1, 11, 12, 13 denote A, J, Q, K respectively. There is no upper or lower limit on the number of cards with the same rank, including Jokers. Cards can be freely rearranged to form sets. Output For each test case output single integer in a separate line: minimum number of points Vishnu can get with a given hand. Example Input: 2 1 2 3 4 5 6 7 8 9 10 11 12 13 3 1 1 3 3 5 5 7 7 9 11 11 13 13 9 Output: 0 60
33,427
Play with Strings (MY02) All you have to do is implement the following algorithm, which is a very popular compression technique. You are given an input string A. (For example ababc) Find all the rotations of A (In this case, they are ababc, babca, abcab, bcaba, cabab) Now sort them (After sorting, we have ababc, abcab, babca, bcaba, cabab) Then arrange them as follows: ababc abcab babca bcaba cabab Now pick out the last column. It is ‘cbaab’. This is the result of this algorithm. Also observe that the 1st row has the original string. (Use 1 indexing) Now, for this problem, you are given the output and the row number that has the original string. For the above example, it is ‘cbaab’ and 1. Given these 2 parameters, you just need to decode it. (i.e. find the original string.) Input: Each test case has 2 lines. 1st line – An integer R that represents the row that contains the original string. 2nd line - A string that represents the output of the above algorithm. (Length of string <=2000) (All characters are lower case). The input is terminated with R=-1. Output: The original string. Sample Input 1 cbaab 3 mnoag -1 Output ababc mango
33,428
Lopov (LOPOV) The difficult economic situation in the country and reductions in government agricultural subsidy funding have caused Mirko to change his career again, this time to a thief. His first professional endeavour is a jewellery store heist. The store contains N pieces of jewellery, and each piece has some mass Mi and value Vi. Mirko has K bags to store his loot, and each bag can hold some maximum mass Ci. He plans to store all his loot in these bags, but at most one jewellery piece in each bag, in order to reduce the likelihood of damage during the escape. Find the maximum total jewellery value that Mirko can “liberate”. Input The first line of input contains two numbers, N and K (1 ≤ N, K ≤ 300 000). Each of the following N lines contains a pair of numbers, Mi and Vi (1 ≤ Mi, Vi ≤ 1 000 000). Each of the following K lines contains a number, Ci (1 ≤ Ci ≤ 100 000 000). All numbers in the input are positive integers. Output The first and only line of output must contain the maximum possible total jewellery value. Example Input: 2 1 5 10 100 100 11 Output: 10 Input: 3 2 1 65 5 23 2 99 10 2 Output: 164
33,429
Organizator (ORGNZ) Unexpected problems with law enforcement have convinced Mirko to take up a less lucrative but less morally ambiguous career: he has become the chief organizer of a team computer science contest. There are N CS clubs that wish to participate in the contest. The presidents of the clubs are quite stubborn and will participate in the contest only if the contest team size makes it possible for all club members to participate. The contest consists of two rounds: qualifications and finals. All teams that are competing must have an equal number of members and all members of one team must belong to the same club. Any number of teams from each club can participate in the qualification round, and the best team from each club earns a spot in the finals. Mirko is aware that, with a new and unproven contest, he needs publicity. For that reason, he wants to set the team size such that the number of individual participants in the finals is as large as possible. Remember, each club that participates has a right to one team in the finals. Furthermore, at least two clubs must participate in the contest, otherwise the contest would be too boring to attract sponsors. Determine the maximum possible number of participants in the finals so that Mirko can double check his team size choice. Input The first line of input contains the positive integer N (2 ≤ N ≤ 200 000), the number of clubs. The second line of input contains N space-separated integers from the interval [1, 2 000 000], the number of members of each club. Output The first and only line of output must contain the maximum possible number of finalists. Example Input: 3 1 2 4 Output: 4 Input: 2 1 5 Output: 2
33,430
Slasticar (SLAST) Organizing CS contests didn't prove very lucrative for Mirko, so he has opened an ice cream and pastry shop. The business was flourishing until, one day, the European Union health inspection decided to pay him a visit. A new directive specifies M banned ingredients which cannot appear in food even in trace amounts. Each ingredient has a serial number consisting of digits 0 through 9. The declaration on each food package lists all the serial numbers of ingredients contained in the respective food item. Mirko must check whether any of his products has a banned ingredient serial number listed on its declaration. However, Mirko, being inept and reckless as always, decided to concatenate all the serial numbers into one long number with length N believing that it will make his job easier. He has borrowed a robot from his friend Slavko. The robot is programmed to check whether a serial number A contains another serial number B as a substring. Let us denote the length of B by L. The robot carries out search as follows: First, it compares the segment of A from position 1 to position L, digit by digit, with the digits in B. Comparison is stopped when a differing digit is found or when the segments are determined to be equal. If the segments are equal, the search is stopped and the match reported. If the segments are not equal, the procedure above is repeated with the segment from 2 to L+1. If those segments aren't equal either, the search continues with segments 3 to L+2, 4 to L+3 etc. If the robot doesn't have a sufficient number of digits to obtain a full segment of length L (for example, starting at character 5 in a serial number with length 8, a segment with length 6 is needed), it will pad the number with '#' signs. For example, the segment of "563232" from position 4 to position 10 is "232####". If the robot reaches the end of the serial number (having tried out all N segments) without having found B, the absence of match is reported. The robot takes one second for each comparison between two digits, and Slavko charges Mirko one dollar per second for using the robot. Help Mirko determine how much money he'll have to pay Slavko for pattern matching! Input The first line of input contains the positive integer N (1 ≤ N ≤ 100 000), the length of the long serial number. The second line of input contains N digits from 0 to 9, the long serial number. The third line of input contains the positive integer M (1 ≤ M ≤ 50 000), the number of banned ingredients. Each of the following M rows contains a single banned serial number. A banned serial number will not exceed 100 000 digits in length. The total length of all banned serial numbers will not exceed 3 000 000 digits. Output Output M integers, one per line. Line i must contain the dollar amount that Mirko needs to pay Slavko for the search for ingredient serial number i. Example Input: 7 1090901 4 87650 0901 109 090 Output: 7 10 3 4 Input: 10 5821052680 4 210526 2105 582 105268 Output: 8 6 3 9 Input: 3 001 1 11 Output: 4
33,431
Even Numbers (EC_CONB) Marina is a college girl who likes to play with all kinds of numbers. One day she was very bored and decided to play around with even numbers. She writes N numbers on the board (odd and even numbers) and then, she modifies only even numbers (for some reason she likes the odd numbers) and reversed its binary representation (from the left to the right ) and replaces each even number. But soon she gets bored and ask  you help in order to automate the conversion process. Input In the first line contains the value of N. This integer is followed by N lines, every one with a positive integer a i (1 ≤ a i ≤ 10 7 ). Output The output will contain N lines, the numbers that are on the blackboard after the conversion process. Example Input: 5 10 8 3 5 2 Output: 5 1 3 5 1
33,432
Decrypt the message ! (DCRYPT) Krishna loves Radha and wants to propose her in a different way. He wants to tell her the message, but he wanted the message to be a surprise. So, he plans to encrypt the message and send the encrypted message to Radha and he also gives the key to decrypt. He thinks that this might be a surprise to Radha. Help Radha to decrypt the message. Rules of encryption : 0 ≤ key ≤ 51 The original message only consists of a-z, A-Z, and space. Spaces are encrypted as '.' If key lies between 0 and 25, then the character is added with the key and modulo is taken and the case is maintained. For eg, if key is 3, then a is decrypted to d and e is decrypted to h. If key lies between 26 and 51, then the character is added with the key and modulo is taken and the case is inverted. For eg, if key is 29, then a is decrypted to D and E is decrypted to h. Input First line consists of t, the number of test cases. (1 ≤ t ≤ 20) For each test case, first line consists of key. 0 ≤ key ≤ 51 Second line consists of the encrypted message S. |S| ≤ 100000 Output For each test case, display the decrypted message in a separate line. Example Input: 1 2 dsz.dsf Output: fub fuh
33,433
Make them equal ! (MKEQUAL) You have an array containing N elements. At any move, you choose two indices i and j (0 ≤ i , j < N and i ≠ j ) and increment value at one index and decrement value at other index. You can make this move any number of times. What is the maximum number of elements which can have the same value (after any number of moves) ? Input First line consists of T , the number of test cases. (1 ≤ T ≤ 100) T sets follow. Each set contains N , the number of elements in the array, in the first line. (1 ≤ N ≤ 100000) Next line of each set consists of N space separated integers (0 ≤ value ≤ 100000) Output Output T lines each containing the required answer. Example Input: 1 4 1 2 3 4 Output:   3
33,434
Lucky Cities (LUCKY) John has recently arrived in Romania for the South Eastern European Regional competitions. John has never been to Romania before so Romanians decided to organize sightseeing tour for him. This tour will include several Romanian cities and none of them will be visited more than once. John will start in one city and will visit some other cities according to a guide tour. At the end of the tour John will return to the starting point. There are N cities numbered from 1 to N and M two-way roads in the country. Each road connects two different cities. Consider a sightseeing tour for John c 1 , c 2 , ..., c n , where each c i denotes a city in Romania. Then all c i must be distinct, c i and c i+1  must be connected by a road, where i=1, 2, ..., n-1, c n and c 1 must be connected by a road as well.  Being a odd person John would like to visit an odd number of cities. The organizers have drawn the plan of all possible tours with an odd number of cities.  Residents of the cities would like John to visit them. So if there is at least one tour passing through some city than this city is called lucky. Your task is to calculate the number of lucky cities in Romania. Input The first line of input contains a single integer T – a number of test cases. Every test case starts with a line containing two integers separated by a single space – N and M. Each of the next M lines will contain two integers a i and b i separated by a single space – the labels of cities that i-th road connects. Output Output should contain T lines – answers for each of the test cases. Constraints 1 ≤ T ≤ 77, 0 ≤ N, M ≤ 100000 (10 5 ), 1 ≤ a i < b i ≤ N Example Input: 1 7 7 1 5 3 5 3 7 1 7 6 7 4 7 4 6 Output: 3 PS: If you like this problem, also see problem BUSINESS
33,435
Update the array ! (UPDATEIT) You have an array containing n elements initially all 0. You need to do a number of update operations on it. In each update you specify l, r and val which are the starting index, ending index and value to be added. After each update, you add the 'val' to all elements from index l to r. After 'u' updates are over, there will be q queries each containing an index for which you have to print the element at that index. Input First line consists of t, the number of test cases. (1 <= t <= 10) Each test case consists of "n u", number of elements in the array and the number of update operations, in the first line (1 <= n <= 10000 and 1 <= u <= 100000) Then follow u lines each of the format "l r val" (0 <= l, r < n, 0 <= val <=10000) Next line contains q, the number of queries. (1 <= q <= 10000) Next q lines contain an index (0 <= index < n) Output For each test case, output the answers to the corresponding queries in separate lines. Example Input: 1 5 3 0 1 7 2 4 6 1 3 2 3 0 3 4 Output: 7 8 6
33,436
Query on a tree VI (QTREE6) You are given a tree (an acyclic undirected connected graph) with n nodes. The tree nodes are numbered from 1 to n . Each node has a color, white or black. All the nodes are black initially. We will ask you to perform some instructions of the following form: 0 u : ask for how many nodes are connected to u , two nodes are connected if all the node on the path from u to v (inclusive u and v ) have the same color. 1 u : toggle the color of u (that is, from black to white, or from white to black). Input The first line contains a number n that denotes the number of nodes in the tree (1 ≤ n ≤ 10 5 ). In each of the following n-1 lines, there will be two numbers ( u , v ) that describes an edge of the tree (1 ≤ u , v ≤ n ). The next line contains a number m denoting number of operations we are going to process (1 ≤ m ≤ 10 5 ). Each of the following m lines describe an operation ( t , u ) as we mentioned above(0 ≤ t ≤ 1, 1 ≤ u ≤ n ). Output For each query operation, output the corresponding result. Example Input 1: 5 1 2 1 3 1 4 1 5 3 0 1 1 1 0 1 Output 1: 5 1 Input 2: 7 1 2 1 3 2 4 2 5 3 6 3 7 4 0 1 1 1 0 2 0 3 Output 2: 7 3 3 Warning: large input/output data, be careful with certain languages
33,437
Linearian Colony (COLONY) Description Linearians are peculiar creatures. They are odd in several ways: Every Linearian is either red or blue. A Linearian colony is a straight line, aligned N-S with the magnetic field. A colony starts with single red Linearian. Every year, each Linearian produces an offspring of the opposite color. After birth, the parent moves just south of the offspring. (Since everyone is born at once, this does make for a lot of jostling, but everyone stays in order.) So a colony grows as follows: N ----------- S Year 0: R Year 1: BR Year 2: RBBR Year 3: BRRBRBBR Year 4: RBBRBRRBBRRBRBBR Given a year and a position along the N-S axis, determine what the color of the Linearian there will be. Input The first line is the year Y (0 <= Y <= 51). The second line is the position P from north to south, 0-indexed (0 <= P < 2^Y). Output The color of the Linearian, either red or blue. Input Input 3 6 51 123456789012345 Output Output blue red
33,438
Triangle (PEGS) Consider the following common single-player game. A board has fifteen holes, arranged in a triangular pattern. Pegs fit in these holes. A valid move is to take a peg and jump in a straight line over an adjacent peg to the an empty hole two positions away from the starting position. The peg that was jumped is removed from the board. The player wins the game when there is only one peg remaining. For example, in the game below, the player wins in two moves. x . . x . . . . . . . . => x . . => . . . . x . . . x . . . . . . . . . . . . . . . . . . x . . In the game below, the player has no possible moves and loses. x . . x . . . . . . . . . . . Given a starting position, determine if it is possible to win. Input The first line is N, the number of starting pegs (0 < N < 15). The next N lines are the pegs' positions. The positions on the board are numbered as following: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Examples Input: 3 1 2 8 Output: yes Input: 14 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Output: yes Input: 13 2 3 13 5 8 11 10 9 12 4 14 15 6 Output: no
33,439
HTML Formatting (FORMAT) Description You have been given formatted text and asked to converted it HTML. Each character may be formatted as bold, italic, underlined, or some combination. In HTML, content between <b> and </b> tags is bold. Content between <i> and </i> tags is italic. Content between <u> and </u> tags is underlined. What is the minimum number of properly nested HTML tags needed to produce a given format? For example, say we wanted to format <i> <b> LookAt </b> Me </i> ! <b> <i> LookAt </b> Me </i> ! has incorrectly nested tags. <b> <i> LookAt </i> </b> <i> Me </i> ! has correctly nested tags, but is longer than necessary. <i> <b> LookAt </b> Me </i> ! is the shortest and uses the fewest number of tags. Input There will be a sequence of 1 to 20,000 numerals. Each numeral denotes the formatting at that position. 0 - no formatting 1 - bold 2 - italic 3 - bold and italic 4 - underlined 5 - bold and underlined 6 - italic and underlined 7 - bold, italic, and underlined (There is no need to actually specify the content, since that will not affect the answer.) The example earlier would be given as 333333220. Output The minimum number of <b> , </b> , <i> , </i> , <u> , and </u> tags required. Input Input Input Input 01 333333220 00110066 12364012375303657213412303 Output Output Output Output 2 4 6 54
33,440
Query on a tree VII (QTREE7) You are given a tree (an acyclic undirected connected graph) with n nodes. The tree nodes are numbered from 1 to n . Each node has a color, white or black, and a weight. We will ask you to perform some instructions of the following form: 0 u : ask for the maximum weight among the nodes which are connected to u , two nodes are connected if all the node on the path from u to v (inclusive u and v ) have a same color. 1 u : toggle the color of u (that is, from black to white, or from white to black). 2 u w : change the weight of u to w . Input The first line contains a number n denoted how many nodes in the tree(1 ≤ n ≤ 10 5 ). The next n -1 lines, each line has two numbers ( u , v ) describe a edge of the tree(1 ≤ u , v ≤ n). The next 2 lines, each line contains n number, the first line is the initial color of each node(0 or 1), and the second line is the initial weight, let's say Wi, of each node(| Wi | ≤ 10 9 ). The next line contains a number m denoted how many operations we are going to process(1 ≤ m ≤ 10 5 ). The next m lines, each line describe a operation ( t , u ) as we mentioned above(0 ≤ t ≤ 2, 1 ≤ u ≤ n , | w | ≤ 10 9 ). Output For each query operation, output the corresponding result. Example Input 1: 5 1 2 1 3 1 4 1 5 0 1 1 1 1 1 2 3 4 5 3 0 1 1 1 0 1 Output 1: 1 5 Input 2: 7 1 2 1 3 2 4 2 5 3 6 3 7 0 0 0 0 0 0 0 1 2 3 4 5 6 7 4 0 1 1 1 0 2 0 3 Output 2: 7 5 7 Warning: large input/output data ,be careful with certain languages
33,441
Sweets (IE1) John has got n  jars with candies. Each of the jars contains a different kind of candies (i.e. candies from the same jar are of the same kind, and candies from different jars are of different kinds). The i -th jar contains m i  candies. John has decided to eat some of his candies. He would like to eat at least a  of them but no more than b . The problem is that John can't decide how many candies and of what kinds he would like to eat. In how many ways can he do it? Input The first line of input contains three integers: n , a  and b , separated by single spaces (1 ≤ n ≤ 10, 0 ≤ a ≤ b ≤ 10000000). Each of the following n  lines contains one integer. Line i+1  contains integer m i  - the amount of candies in the i -th jar (0 ≤ m i ≤ 1000000). Output Let k  be the number of different ways John can choose the candies to be eaten. The first and only line of output should contain one integer: k  mod 2004 (i.e. the remainder of k  divided by 2004). Example Input: 2 1 3 3 5 Output: 9 John can choose candies in the following ways: (1, 0), (2, 0), (3, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (2, 1)
33,442
Journey (IE2) In Byteland there are n cities numbered from 1 to n . These cities are connected by a network of m bidirectional roads. It is known that each pair of cities is connected by at most one road. Byteman admitted recently that he likes some cities more than others. More precisely, he spends his time especially well in cities with numbers from 1 to k , so during every journey he visits each of them at least once. Byteman's journey is a sequence of d cities, such that each pair of consecutive cities is connected by a road. The journey can start and end in any city. Your task is to compute the number of distinct journeys around Byteland that Byteman can make. Because this number might be quite large, it will be enough to find it modulo 10 9 + 9 . Input The first line of input contains four integers n, m, k and d (1 ≤ n ≤ 20, 1 ≤ k ≤ min( n , 7), 1 ≤ d ≤ 10 9 ), separated by single spaces. The following m lines contain descriptions of connections between cities of Byteland. A description of a road consists of two numbers a i , b i (1 ≤ a i , b i ≤ n , a i ≠ b i ), separated by a single space and denoting the numbers of cities connected by the i 'th road. Output The output should contain one integer, denoting the number of distinct journeys that Byteman can make, modulo 10 9 + 9 . Example Input: 4 4 2 3 1 2 2 3 3 1 2 4 Output: 10
33,443
Endless Knight (IE4) In the game of chess, there is a piece called the knight. A knight is special -- instead of moving in a straight line like other pieces, it jumps in an "L" shape. Specifically, a knight can jump from square (r1, c1) to (r2, c2) if and only if (r1 - r2) 2 + (c1 - c2) 2  = 5. In this problem, one of our knights is going to undertake a chivalrous quest of moving from the top-left corner (the (1, 1) square) to the bottom-right corner (the ( H ,  W ) square) on a gigantic board. The chessboard is of height  H  and width  W . Here are some restrictions you need to know. The knight is so straightforward and ardent that he is only willing to move towards the right  and  the bottom. In other words, in each step he only moves to a square with a bigger row number and a bigger column number. Note that, this might mean that there is no way to achieve his goal, for example, on a 3 by 10 board. There are  R  squares on the chessboard that contain rocks with evil power. Your knight may not land on any of such squares, although flying over them during a jump is allowed. Your task is to find the number of unique ways for the knight to move from the top-left corner to the bottom-right corner, under the above restrictions. It should be clear that sometimes the answer is huge. You are asked to output the remainder of the answer when divided by 10007, a prime number. Input Input begins with a line containing a single integer,  N .  N  test cases follow. The first line of each test case contains 3 integers,  H ,  W , and  R . The next  R  lines each contain 2 integers each,  r  and  c , the row and column numbers of one rock. You may assume that (1, 1) and ( H ,  W ) never contain rocks and that no two rocks are at the same position. Output For each test case, output a single line of output, prefixed by "Case # X : ", where  X  is the 1-based case number, followed by a single integer indicating the number of ways of reaching the goal, modulo 10007. Limits 1 ≤  N  ≤ 100 0 ≤  R  ≤ 10 1 ≤  W  ≤ 10 8 1 ≤  H  ≤ 10 8 1 ≤  r  ≤ H 1 ≤  c  ≤ W Example Input: 5 1 1 0 4 4 1 2 1 3 3 0 7 10 2 1 2 7 1 4 4 1 3 2 Output: Case #1: 1 Case #2: 2 Case #3: 0 Case #4: 5 Case #5: 1
33,444
Some Sums (SOMESUMS) After giving a heartwarming, inspirational speech to the sorority sisters of Delta Gamma at the University of Maryland, Michael Shannon was assaulted on the street by an armed mathematician, who defined a function f as follows: The mathematician presented Shannon with an ultimatum: You will write a program to calculate this function modulo 10 9 +7 for various values of m , n , and k within the given constraints XOR I will shoot you with this gun! As the mathematician lay recovering in his hospital bed, a Sigma Nu brother who had witnessed the event gingerly approached him and said, "Professor Martinson, I've written a program to solve your problem, but the online judge on your website keeps telling me the answer is wrong. Please tell me what the problem is. Submission ID 571972597." Wearily, Martinson replied, "Have you written a brute force program to verify your program's output for smaller cases?" The Sigma Nu brother replied, "Sorry, what did you say? I wasn't listening. Hey, are you going to eat that?" He then took the professor's chocolate pudding and went home to his lovely girlfriend from Zeta to enjoy the rest of the evening. Input In the first line, an integer T , the number of test cases. Then T lines containing integers m , n , and k separated by spaces. Output T lines containing the value of f ( m , n , k ) modulo 10 9 +7 for each test case. Constraints 1 ≤ T ≤ 20000 0 ≤ m ≤ 1000 0 ≤ n ≤ 10 9 0 ≤ k ≤ 1000 Example Input: 5 0 0 0 1 100 1 2 100 0 2 100 1 100 100 100 Output: 1 5050 5151 171700 143422859 Additional Info There are two randomly generated data sets, one with T = 10000 and the other with T = 20000. The distributions are close to uniform random. At the time of publication, my C code runs in 0.69s and my Python 2.7 code runs in 24.70s. The Python code is about 1KB, not golfed.
33,445
Nadal vs Djokovic (RAFANOLE) Rafael Nadal vs Novak Djokovic is probably the fiercest rivalry in tennis right now. Now your task is very simple. You are given a string containing the scores of a single set (a set consists of many games) between these two stalwarts. N denotes Nadal and D denoted Djokovic. For those who are new to tennis, have a look of the rules online. Anyway small description about the rules: Now how a player wins a single game? In a game scores are incremented as follows: 15, 30, 40. A player wins if scores are like 40-0, 40-15, 40-30. If tied at 40-40, it is called deuce. If N wins next he has an advantage and if he loses the next volley he comes back to deuce. After advantage if the player wins the next volley he wins that game. Simply put the player who wins 6 games first (provided he has won two games more than his opponent) wins the set. For example, 6-1, 6-2, 6-3, 6-4 are all valid. If 1 player has won 6 games and the other has won 5 games the match continues. (7-5 is also a valid scoreline.) If both the players are deadlocked at 6-6, then we have a tiebreaker. In the tiebreaker the scores are counted normally (1, 2, 3...) The person who reaches 7 points first and is at least 2 more than his opponent wins the set. Example: 7-0, 7-1, 7-2 ... 7-5 are valid. If the score is 7-6 the match proceeds until one of the players scores two points more than the other, for example: even 10-8 is valid. Input 1st line - number of test cases Next T lines consist of strings denoting who won a volley. Output Output the winner, their score, and the tie breaker score if any in the first line. Output the loser and their score on the second line. See the sample out for the required formatting. Example Input: 2 N N N N N N N N N N N N N N N N N N N N D D D D D D D D N N N N D D D D N N N N D D D D N N N N D D D D N N N N D D D D N N N N D D D D N N N N D D D D N N N N D D D D D D N N N N N D Output: N 6 D 2 D 7 (7-5) N 6
33,446
Help Your Commander (HELPCOMM) A good war commander must take quick decisions, and at the same time be a good strategist. One of the functions of the commander is to delegate soldiers to several strategic points, such that the enemy can be caught surprised and be defeated. There are several strategic points at the battle field, as well as several routes that connect these points. Your field is, however, being bombarded, and these routes are not so safe as they were. Once a bomb falls at one route, such terrain becomes irregular and your crossing becomes impossible. To deal with such problem, the commander ordered a new task to some soldiers: find new routes. The commander asked your help to calculate the shortest path between the base of operation and the strategic points. You will be informed about the initial state of the battle field, with N strategic points (being the point 1 the base of operation) and M routes. As the bombs falls over some routes, and other routes are found by the soldiers, you must update your map such that your commander can make good use of such information. Good luck, the country depends on you. Input The input contains several test cases. Each test case begins with two integers, N and M (2 ≤ N ≤ 1000 and 1 ≤ M ≤ 10000), representing, respectively, the number of strategic points and the number of routes that connects two strategic points. After that, there will be M lines, each one with three integers U , V and W (1 ≤ U , V ≤ N and 1 ≤ W ≤ 100) each, representing that there is a route that connects the point U to the point V , in unique direction, with distance W . There will be, then, an integer Q (1 ≤ Q ≤ 1000), that represents the number of consults or updates that will be done over the routes. At the next Q lines there will be a letter and a determined number of integers. If the letter is a R , there will be two integers U and V (1 ≤ U , V ≤ N ), indicating that the route that used to connect the point U to the point V was bombed. In the case that the letter is a I , there will be three integers U , V and W (1 ≤ U , V ≤ N and 1 ≤ W ≤ 100), indicating that a new route was found, which connects the point U to the point V , with distance W . And in the case that the letter is a P , there will be one integer V (1 ≤ V ≤ N ), and you must inform to the commander what is the shortest distance between the base of operation and the strategic point V . The input ends when N = M = 0. Output For each test case there will be a not defined number of output lines. When the commander order to know the shortest distance between the base of operation and a strategic point (letter P ), such distance must be print in an unique line. If it is not possible to reach such strategic point, the number -1 must be printed. There must have a blank line after each test case. Example Input: 3 3 1 2 2 2 3 3 1 3 4 5 P 3 R 2 3 P 3 I 2 3 1 P 3 Output: 4 4 3
33,447
Divisible by 6 and 9 (SNGDIV69) Let num (> 0) be n (> 0) digit(s) positive integer. num is represented as N 1 N 2 N 3 N 4 ...N n-2 N n-1 N n , where N i is the i th digit of num from left (0 < i < n+1). Digits of num are sorted in descending and ascending order respectively and this sorting generates two new positive integers num dsc and num asc . The difference between the numbers is diff num = num dsc  - num asc , if diff num  is divisible by both 6 and 9, then we say that num is a magic number. Let sum digits be defined as following number = diff num do { number = sum of digits of number } while (number > 10) sum digits = number Input First line of input is t (< 101), total number of test cases. Each test case has n (< 10001) as its first input and next n lines contains num (< 10 100 ). Output For each test case, write exactly n lines containing two or three specifications without space: Y if num is magic number otherwise N . Let sum digits = c, ZER if c is 0 (zero), ONE if c is 1 (one) if c > 1, EP if c is even and prime, ENP if c is even but not prime, OP if c is odd and prime or ONP if c is odd but not prime. Let diff num = d, If num is not a magic number then print EQL if d is not divisible by both 6 and 9, LTN if d is not divisible by 6 only, GTN if d is not divisible by 9 only. Example Input: 1 2 31 100 Output: YONP NONPLTN 0 is divisible by 6 and 9 :)
33,448
Modems (EC_MODE) A Oruro province wants ALL the towns to have Internet access and to communicate with each other by at least one channel (not necessarily direct). The engineer in charge asks you to help him determine the minimum cost of providing this access. There are N towns in total (1 ≤ N ≤ 1000). UTP can be used only up to range R (1 ≤ R ≤ 10000). If this distance is exceeded, optical fiber must be used instead. The unit cost of using UTP cable is U and the unit price of the optical fiber is V (U ≤ V; 1 ≤ U, V ≤ 10). There are also W satellite modems purchased (1 ≤ W < N). These satellite modems can be placed in any town. Satellite modem will allow a town to use the internet and communicate with any other modem in the province. Input The first line contains the number of test cases. First line of each test case consists of five integers N, R, W, U, V. Then N lines follow, each with integer pair x i , y i (-10000 ≤ x i , y i ≤ 10000), the coordinates of i-th town. Output For each case, print a line of the form: Caso #TC: A B Where TC is the test case number, A is the total cost of using UTP cable and B is the total cost of using optical fiber. Print both A and B rounded to 3 decimal places. Example Input: 2 3 1 1 1 1 0 0 0 1 1 0 6 1 3 2 3 0 0 0 2 2 0 3 2 2 3 3 3 Output: Caso #1: 2.000 0.000 Caso #2: 4.000 6.000
33,449
Sir and the Guitar (CSHOWB) After teaching guitar to Jimmy Page (Led Zeppelin Band Guitarist), Sir Jadeja has decided to do something new. Sir Jadeja took out his guitar and started playing a melody he composed when he was 2 months old. The guitar as usual has 6 strings denoted by numbers through 1 to 6. Each string is divided into P frets denoted by numbers 1 to P. A melody is a sequence of tones, where each tone is produced by picking a string pressed on a specific fret (for example: 4th string pressed on 8th fret). If a string is pressed on several frets, the produced tone will be the one corresponding to the highest of those frets. For instance, if the 3rd string is already pressed on the 5th fret, and the tone which corresponds to the 7th fret is to be produced, the string can be pressed on the 7th fret and picked without releasing the 5th fret. If a tone that corresponds to the 2nd fret on the same string is to be produced next, it is necessary to release both 5th and 7th frets and only then press 2nd. Sir Jadeja feeling tired wants to play the melody with minimum number of finger movements. Note that press or release a single fret counts as one finger move. String picking is not a finger move, but rather a guitar pick move and should not be counted. Remember that picking a string with not affect frets being pressed on other string. You can assume that Sir Jadeja has enough fingers to press all the frets on all string at the same time (yes, that many). Input: First line contains two integers: N (N <= 500000) and P (2 <= P <= 300000). N denotes number of tones in the melody and P denotes number of frets. The next N lines describe the fields for the corresponding tones: the number of the string and the number of the fret, respectively. Tones must be played in the order they are described. Output: Print a single integer: minimum number of finger movements that need to be made. Examples Input 1: 5 15 2 8 2 10 2 12 2 10 2 5 Output 1: 7 Input 2: 8 15 2 8 2 10 2 12 3 7 2 10 3 5 2 5 3 3 Output 2: 12 Explanation: For set 1: All the tones played are produced by picking the 2nd string . First the frets 8, 10, 12 are pressed in order(three movements). Then the 12th fret is released to produce the second tone again (fourth movement). Finally the fifth fret is pressed followed by the release of frets 10 and 12( 5th, 6th and 7th ).
33,450
Statistics Applied (EC_ESTA) In this problem we will be looking for medians of data set. Median is the central element in ordered data group. For example: for the set {2, 6, 3, 3, 2} the median would be 3. In general, if we have n elements {a1, a2, a3 ... an}, we define the median as element a (n+1)/2 if n is odd and (a n/2 +a n/2+1 )/2 otherwise. You will be given N numbers and you must calculate N medians. i-th median is taken on the subset [a 1 , a 2 , a 3 ... a i ] for 1 ≤ i ≤ N. Input The first line contains the number of test cases. Each case consists of an integer N (1 ≤ N ≤ 100000). N integers a i (0 ≤ a i < 2 31 ) follow, elements in data set. Output For each case, print N lines with the medians. If the result is non-integral, print the exact value using decimal point (see example). Example Input: 2 4 3 5 7 3 2 3 4 Output: 3 4 5 4 3 3.5
33,451
Estimation (EST) “There are too many numbers here!” your boss bellows. “How am I supposed to make sense of all of this? Pare it down! Estimate!” You are disappointed. It took a lot of work to generate those numbers. But, you’ll do what your boss asks. You decide to estimate in the following way: You have an array A of numbers. You will partition it into k contiguous sections, which won’t necessarily be of the same size. Then, you’ll use a single number to estimate an entire section. In other words, for your array A of size n, you want to create another array B of size n, which has k contiguous sections. If i and j are in the same section, then B[i]=B[j]. You want to minimize the error, expressed as the sum of the absolute values of the differences (∑|A[i]-B[i]|). Input There will be several test cases in the input. Each test case will begin with two integers on a line, n (1 ≤ n ≤ 2,000) and k (1 ≤ k ≤ 25, k ≤ n), where n is the size of the array, and k is the number of contiguous sections to use in estimation. The array A will be on the next n lines, one integer per line. Each integer element of A will be in the range from -10,000 to 10,000, inclusive. The input will end with a line with two 0s. Output For each test case, output a single integer on its own line, which is the minimum error you can achieve. Output no extra spaces, and do not separate answers with blank lines. All possible inputs yield answers which will fit in a signed 64-bit integer. Example Input: 7 2 6 5 4 3 2 1 7 0 0 Output: 9
33,452
Divisors (EC_DIVS) Misael is a child that loves maths. This year he learned about operations with decimal numbers, simplifying fractions, maximum and minimum of a set. But Misael is not an ordinary child. He knows programming and he proposed a challenge: He will give you a list of numbers and you must calculate all common divisors for all numbers on that list. The task is simple, but Misael offers you something even more interesting. The size list is variable, he can add as well as remove numbers. However Misael doesn't like the prime divisors, so you should exclude those numbers from the list. Input The first line contains the number of test cases, and each case consists of an integer N (1 ≤ N ≤ 100000): the number of operations to perform. Each operation can be one of 3 types: UPD ADD x : Updating the list by adding the element x to the list. UPD REM x : Update the list by removing the element x from the list. CON :  print common divisors to the entire list. The range of values ​​of x is 1 ≤ x ≤ 10000. There can be more that one element with the given value on the list. When removing element, you only remove one element with the given value. It's guaranteed that at least one such element will exist. Output For each type operation CON print a line with non-prime common divisors listed in ascending order. If the list is empty, print -1. Example Input: 1 6 UPD ADD 6 CON UPD ADD 12 CON UPD REM 6 CON Output: 1 6 1 6 1 4 6 12
33,453
Critical Edges (EC_P) This time I will not bore you with a long and boring sentence. Give a connected graph, you must find all the edges that are critical, in other words you must find the edges which when removed divide the graph. Input The first line contains a integer NC (1 ≤ NC ≤ 200), the number of test cases. Then follow NC test cases. Each case begins with two integers N (1 ≤ N ≤ 700) and M (N-1 ≤ M ≤ N * (N-1) / 2), the number of nodes and the number of edges respectively. Then follow M lines, each with a pair of integers a b (1 ≤ a, b ≤ N) indicate that between the node a and the node b there is a edge. Output For each test case print the list of ways to protect the following format: Caso #n t x1 y2 x2 y2 ... xt yt Where n is the case number (starting from 1), t is the total of critical edges, list elements x i  y i indicates, for each line, there is a critical edge between the node x i and node y i (1 ≤ x i i ≤ N). In addition, the list should be sorted in non-decreasing order first by x i and then by y i . Also  x i  < y i  must hold. If there isn't any critical edge print: "Sin bloqueos" (quotes for clarity). Example Input: 3 5 4 1 2 4 2 2 3 4 5 5 5 1 2 1 3 3 2 3 4 5 4 4 6 1 3 1 4 2 1 3 2 4 2 4 3 Output: Caso #1 4 1 2 2 3 2 4 4 5 Caso #2 2 3 4 4 5 Caso #3 Sin bloqueos
33,454
Encoded Coordinates (ENCODE) You have been monitoring a terrorist cell that is planning a big attack somewhere close. The terrorists have been sending encoded coordinates to each other, and you suspect that the attack will happen at one of the locations described by these coordinates. You have intercepted the relevant communications for a series of locations you want to investigate. Every location consists of a separate x and y coordinate, each being a non-negative integer smaller than some prime number P. Both coordinates are encoded separately using the same process. A source has given you information on the process of decoding a single coordinate. The input of this process consists of five values: A, B, C, K and N. Central to the decoding process is a collection of three functions, defined in terms of each other and the input value K: F(n + 1) = G(n) + H(n) G(n + 1) = K * F(n) + H(n - 1) H(n + 1) = F(n) + K * G(n) The values A, B and C are used to initialize these functions as follows: F(1) = A, G(1) = B, H(1) = C The decoded coordinate is the value of F(N) mod P . As you might have noticed, there is some crucial information missing: you need the value of H(0) to calculate G(2). While you do not have this value, you do know that the x and y coordinate use the same value for H(0). Luckily, you have managed to already obtain the x coordinates for the locations. Your colleagues have suggested that this does not give you enough information to calculate the y coordinates, but you want to prove them wrong. Input On the first line one positive number: the number of test cases, at most 100. After that per test case: # one line with the prime number P (2 ≤ P ≤ 19997). # one line with five space-separated integers Ax, Bx, Cx, Kx and Nx (0 ≤ Ax, Bx, Cx, Kx < P and 1 ≤ Nx ≤ 10^9): the parameters for the x coordinate. # one line with five space-separated integers Ay, By, Cy, Ky and Ny (0 ≤ Ay, By, Cy, Ky < P and 1 ≤ Ny ≤ 10^9): the parameters for the y coordinate. # one line with one integer x (0 ≤ x < P): the x coordinate. Output Per test case: # one line with one integer: the calculated y coordinate. If your colleagues are right, and there is not exactly one valid y coordinate, print “UNKNOWN” on a single line instead. Example Input: 2 11 2 3 5 7 4 4 6 8 9 7 5 7 1 6 2 5 1 3 4 2 5 3 1 Output: 7 UNKNOWN
33,455
Psycho Function (PSYCHO2) The number N is called “ Psycho Number ”. Psycho Number is calculated as follows: First, If we factorize N, then we have some prime and their power. Assume that, there are M powers. From M powers, you should count the number of even and odd powers. Then if the number of even power is strictly greater than odd power, then we call the number N is “ Psycho Number ”, otherwise the number N is call “ Ordinary Number ”. As for example, if N = 67500 then prime factorization, 67500 = 2 2 x 3 3 x 5 4 . Count even powers and odd powers. This number have 2 even power (2, 4) and 1 odd power (3). Since even power 2 (2, 4) is greater than odd power 1 (3), so the number 67500 is a Psycho Number. bool isPsycho( long long K, long long b, long long p) { N = numberoftrailingzeros(K!) * lastdigit(b p ); if (N == psychonumber) return true; else return false; } For example, if k = 10, b = 12, p = 1 then the N is 4 and it's a psycho number. 10! = 3628800, number of trailing zeros is 2. 12 1 = 12, last digit is 2. so N = 4 then 4 = 2 2 . Even power is greater than odd power, so the number 4 is a Psycho Number. Input: An integer T (1 ≤ T ≤ 10 5 ) denoting the number of test cases followed by T lines. Each line containing K (1 ≤ K ≤ 4×10 6 ), b (0 ≤ b ≤ 10 4 ), and p (0 ≤ p ≤ 10 17 ). Output: For each case print “ Psycho Number ” or “ Ordinary Number ”. Sample Input 2 5 2 5 10 12 1 Output Ordinary Number Psycho Number Note : 0 and 1 is not a psycho number. Psycho 1: Psycho Psycho 3: Make Psycho Psycho 4: Psycho34 (easy) Problem setter: Shipu Ahamed, Dept. of CSE, Bangladesh University of Business and Technology (BUBT)
33,456
Black Widow Rings (BWIDOW) Black Widow has a collection of N (numbered 1 to N) Rings. She uses the rings to attack the enemies. She has decided to use one ring for distraction. She will first throw the distraction ring and then all the other rings will be thrown through it (one at a time). Each ring has an inner and outer radius. A ring R1 will pass through ring R2 only if the outer radius of R1 is less than the inner radius of R2. If she can chose a distraction ring from the given collection print the index of the ring (1-based), else print -1. Input The first line of the input contains an integer T denoting the number of test cases. The first line of each test case contains a single integer N denoting the number of Rings. Next N lines consists of Inner and Outer Radius of the ith Ring - r , R . 1 ≤ T ≤ 100 2 ≤ N ≤ 1000 1 ≤ r < R ≤ 10 7 ( Edited: r and R are integer) Output For each test case print the desired result in separate line. Example Input: 2 3 2 3 6 8 3 5 3 4 5 5 8 3 10 Output: 2 -1
33,457
Training Land of Fury (NFURY) S.H.I.E.L.D. is recruiting soldiers for the battle with Loki's army. Nick Fury has come to Manhattan to find a large area of land to be used for training purposes. He meets a popular landlord there who is a little foolish by nature. He gives square pieces of land with integral sides and charges on the basis of number of pieces of land bought irrespective of how large a piece of land is. Fury has to buy exactly A square units of land. Help Fury by determining the minimum number of pieces that should be bought in order to minimize the expenditure. Input The first line of the input contains an integer T denoting the number of test cases. The first line of each test case contains a single integer A denoting the area that nick fury want to buy. 10 ≤ T ≤ 100000 1 ≤ A ≤ 1000 Output For each test case print the minimum number of pieces that should be bought. Example Input: 4 1 2 3 10 Output: 1 2 3 2 Explanation For the last test case 10 the answer will be 2. 10 can be expressed as sum of minimum two squares that is 10 = 3 2 +1 2 .
33,458
Finding the Tesserect (TESSER) Dr. Bruce Banner had estimated a coarse location of Tesseract through gamma radiation emission tracing experiment. It was estimated that Tesseract was hidden somewhere within the Alps mountains. Captain America was given the assignment to look for the Tesseract and bring it back to S.H.I.E.L.D. While roaming through the mountains of Alps, Captain America looked at the height of hills and clicked a panoramic photograph of mountains. This gives an idea of the heights of mountains. Meanwhile Banner was able to determine a continuous pattern of mountains behind which the Tesseract lies and transmitted a message containing the pattern. The message is a string consisting of characters 'G', 'L' and 'E' where G means greater, L means less and E means equal. But this estimation is likely to go wrong due to not considering environmental disturbances that may have arisen in the medium during the experiment. Pattern estimate is correct only if one can find a set of consecutive heights out of the given N heights satisfying the message pattern (if G is first character of the message string then second height should be greater than the first height of the selected set and so on) Captain America seeks your help to find out whether the estimation is correct or wrong so that Captain America could proceed his tasks. Input The first line of the input contains an integer T denoting the number of test cases. Each test case consists of 3 lines. The first line of each test case contains a single integer N denoting the number of hills. Second line of each test case consists of N integers (a_1, a_2 ... a_n) , the heights of hills. Third line contains the message pattern. 1 ≤ T ≤ 10 5 2 ≤ N ≤ 10 5 1 ≤ a_i ≤ 10 9 1 ≤ Length of Message Pattern ≤ N-1 Output For each test case print 'YES' if the pattern estimation is correct. Else print 'NO'. Example Input: 1 5 1 2 3 4 1 GGL Output: YES   Explanation Answer is "YES", because 2 3 4 1 satisfies GGL pattern, i.e. 3 is greater than 2, 4 is greater than 3, 1 is less than 4.
33,459
Destroying the Weapon Warehouse (IMBOX) Iron man is hovering over enemy territories. He comes across their weapons warehouse. The weapons are stored in N rectangular boxes. No two boxes share edges. Boxes may be located inside other boxes but no two boxes will partially overlap each other. Iron man can destroy a box by sending a magnetic pulse with power equal to area of the box (irrespective of the height of the box). This pulse will destroy anything present inside the box. Since Iron man is running low on power, he conveys the 2-D coordinates of all the boxes (as seen from the top view) to Jarvis(artificial intelligence) to calculate the minimum total power of the pulses that will be used to destroy all the boxes. Help Jarvis in determining the total effective area of the weapon warehouse to which the beam needs to be directed to destroy all the boxes. Input The first line of the input contains an integer N denoting the number of rectangular boxes. N lines follow. Each following line contains 4 integers- x_1, y_1, x_2, y_2 where coordinates (x_1,y_1) and (x_2,y_2) uniquely identify a rectangular box. 1 ≤ N ≤ 10 5 -10 8 ≤ x_1, y_1, x_2, y_2 ≤ 10 8 Output Print the total effective area to be destroyed. Example Input: 3 0 0 2 2 -1 -1 4 4 5 5 8 8 Output: 34 Explanation In the given test case, first box lies completely inside the second box so we need not to consider that box in calculating the total effective area. Therefore the answer will simply be the sum of areas of the second and third boxes that is 25+9=34
33,460
Chess Board of Avengers (AVCHESS) The Avengers become divided, both over how to approach Loki and the revelation that S.H.I.E.L.D. plans to harness the Tesseract to develop weapons as a deterrent against hostile extraterrestrials. The argument is raised between Captain America, Iron man and Thor each having his own point to keep. Agent Natasha Romanoff comes up with a non-violent solution to this argument by suggesting a variant of the game of chess for three players. This time chessboard contains only a knight, a rook and a bishop. In this game, first Captain America takes his turn, next Iron Man and then Thor. After Thor's turn, this sequence repeats. Captain America can only move knight, Iron Man rook, and Thor bishop and each player can move their respective piece to an empty position. The rook can move any number of squares horizontally or vertically, but may not leap over other pieces. The bishop can move any number of squares diagonally, but may not leap over other pieces. The knight' move forms an "L"-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The knight is the only piece that can leap over other pieces. The objective of game is to place rook at the initial position of knight, bishop at initial position of rook and knight at initial position of bishop. That is, if the initial position of knight, rook and bishop is (x1, y1), (x2, y2) and (x3, y3) , respectively, then the final position of them should be (x3, y3), (x1, y1), (x2, y2) respectively. Input The first line of the input contains an integer T denoting the number of test cases. Each test case consists of exactly one line containing 6 space separated integers x1 y1 x2 y2 x3 y3 . x1 y1 represents the initial position of Knight. x2 y2 represents the initial position of Rook. x3 y3 represents the initial position of Bishop. T = 5 0 ≤ x1, y1 ≤ 7 0 ≤ x2, y2 ≤ 7 0 ≤ x3, y3 ≤ 7 No pair of initial positions are equal, i.e., ( x1 , y1 ) != ( x2 , y2 ) && ( x1 , y1 ) != ( x3 , y3 ) && ( x2 , y2 ) != ( x3 , y3 ) Output For each test case, print the minimum number of turns required to achieve this objective. If the desired configuration is not reachable print -1.   Example Input: 1 0 0 5 1 3 3 Output: 5 Explanation Starting Points of Knight[0,0], Rook[5,1] and Bishop[3,3] can be changed to Knight[3,3], Rook[0,0], Bishop[5,1] in the following five steps: Knight - [0,0] to [1,2] Rook - [5,1] to [5,0] Bishop - [3,3] to [5,1] Knight - [1,2] to [3,3] Rook - [5,0] to [0,0] There is no way to get the required final configuration in less than 5 steps.
33,461
Thor vs Frost Giants (TBATTLE) Thor is caught up in a fierce battle with Loki's army. This army consists of frost giants that have magical powers with them. Their strength levels gets multiplied when they are together. Giants are not highly skilled in the arts of combat, but their sheer size and strength make them formidable opponents even for the Asgardian gods. Thor is no exception. They recover very fast from physical injury but their recovery slows down when they are exposed to extreme heat. Thor's hammer can generate heat only in multiples of heat quantum N . Frost giants get killed only when their combined strength level is exactly equal to the heat level of the hammer. Thor is interested in killing a continuous stretch of frost enemies with a throw of his hammer with a preference to kill closer enemies first. Continuous stretch is defined as a set of consecutive elements. Help Thor to determine the minimum stretch of frost giants that could be killed in a throw. In case of multiple minimal stretches, output the indices of that stretch that has lowest starting index. If there is no such continuous stretch possible then print -1. Input The first line will contain N , the number of Frost Giants in Loki's army and the Heat quantum. The second line will contain N integers (a 0 , a 2 ... a n-1 ) - the strength of each frost giant. Minimum stretch of the army should be 1. 1 ≤ N ≤ 100000 1 ≤ a i ≤ 100000 Output Output the range of the minimum stretch of frost giants that could be killed in a throw. In case of multiple minimal stretches, output the indices of that stretch that has lowest starting index. If there is no such continuous stretch possible then print -1. Example Input: 3 1 2 9 Output: 2 2 Input: 5 2 3 4 8 9 Output: -1 Input: 10 2 4 3 5 17 4 7 5 2 15 Output: 7 8 Explanation Input #1: Thor can only kill the stretch [2, 2] as this is the minimum length range with strength, multiple of 3. Input #2: There is no stretch of frost giants that have combined strength as a multiple of 5. Input #3: There are many stretches of frost giants that have strength as multiple of 10. But the minimal stretch with the least indices is from [7, 8]. Minimum size stretches are [7, 8] and [8, 9]. Out of them we select [7, 8].
33,462
Putnik (PUTNIK) Chances are that you have probably already heard of the travelling salesman problem. If you have, then you are aware that it is an NP-hard problem because it lacks an efficient solution. Well, this task is an uncommon version of the famous problem! Its uncommonness derives from the fact that this version is, actually, solvable efficiently.  The travelling salesman is on a mission to visit N cities, each exactly once. The cities are represented by numbers 1, 2 ... N. What we know is the direct flight duration between each pair of cities. The salesman, being the efficient man that he is, wants to modify the city visiting sequence so that the total flight duration is the minimum possible.  Alas, all is not so simple. In addition, the salesman has a peculiar condition regarding the sequence. For each city labeled K must apply: either all cities with labels smaller than K have been visited before the city labeled K or they will all be visited after the city labeled K. In other words, the situation when one of such cities is visited before, and the other after is not allowed.  Assist the poor fellow in his ambitious mission and calculate the minimum total flight duration needed in order to travel to all the cities, starting from whichever and ending in whichever city, visiting every city exactly once, so that his peculiar request is fulfilled.  Input The first line of input contains the positive integer N (2 ≤ N ≤ 1500), the number of cities. Each of the following N lines contains N positive integers from the interval [0, 1000]. The number in B th place in the A th row represents the flight duration between cities A and B; that number is equal to the A th number in the B th row. When A = B, that number is 0. Otherwise, it is a positive value. Output The first and only line of output must contain the required minimum total flight duration.  Example Input: 3 0 5 2 5 0 4 2 4 0 Output: 7 Input: 4 0 15 7 8 15 0 16 9 7 16 0 12 8 9 12 0 Output: 31 Clarification of the first example: the optimal sequence is 2, 1, 3 or 3, 1, 2. The sequence 1, 3, 2 is even more favorable, but it does not fulfil the salesman's condition. Clarification of the second example: the sequence is either 3, 1, 2, 4 or 4, 2, 1, 3.
33,463
Make Psycho (PSYCHO3) Problem Statement The number N is called Psycho Number . Psycho Number is calculated as follows: First, If we factorize N, then we have some prime and their power. Assume that, there are M powers. From M powers, you should count the number of even and odd powers. Then if the number of even power is strictly greater than odd power, then we call the number N is “ Psycho Number ”, otherwise the number N is call “ Ordinary Number ”. As for example, if N = 67500 then prime factorization,  67500 = 2 2 x 3 3 x 5 4 . Count even powers and odd powers. This number have 2 even power (2, 4) and 1 odd power (3). Since even power 2 (2, 4) is greater than odd power 1 (3), so the number 67500 is a Psycho Number. Now, Given an integer K , your task is to find whether it is possible to form a subset consisting of only psycho numbers that sum up to exactly K , or not. Note: 0 and 1 are not psycho numbers. Input The first line of the input contains an integer, T (1 ≤ T ≤ 2000) indicating the number of test cases. For each test case, two lines appear, the first one contains a number N (1 ≤ N ≤ 100), representing the length of the numbers, and K (1 ≤ K ≤ 10 5 ). The second line of each test case contains the sequence of integers p 1 , p 2 , ..., p n (0 ≤ p i ≤ 1100). It's a mix of psycho and ordinary numbers. Output: For each case print  “ Yes ” if possible to make K , otherwise “ No ”. Example Sample Input 3 5 20 4 5 12 20 16 5 3 3 5 9 2 7 3 24 4 4 16 Sample Output Yes No Yes Explanation 1st test case : psycho numbers: 4 and 16. Possible numbers: 4, 16 and 20 (4+16). k is 20 so you can make this number. 2nd test case : psycho numbers: only 9. k is 3 but it's not possible to make subset of psycho numbers with sum equal to k. 3rd test case : psycho numbers: 4 4 16. Possible numbers: 4, 16, 20 (16 + 4) and 24 (16 + 4 + 4). k is 24 so you can make this number. Psycho 1: Psycho Psycho 2: Psycho Function Problem setter: Shipu Ahamed, Dept. of CSE Bangladesh University of Business and Technology (BUBT)
33,464
Palin Square (PLSQUARE) Kids just learnt about palindrome strings yesterday. Today, the teacher today was going to teach them about square shapes. But kids were still excited about palindrome strings. Therefore, the teacher came up with an idea combining square and palindrome in a game. The teacher gave to kids a square board size of n, which is n row(s) × n column(s). Each row is a string of n character(s). Then, the teacher asked them to find the palindrome sub-square, which has maximum size. A palindrome sub-square is a sub square in board such that characters in each row of the sub square give out a palindrome string, and characters in each column of the sub square also give out a palindrome string. Remember: A palindrome string is a string that has the property of reading the same in either direction, e.g. 'racecar', 'solos'. When the teacher comes out from toilet, he was too happy and forgot the sub square in solution… Your task now is to help him to find out the maximum size of the palindrome sub square in the given board. Input: The first row contains an integer n, which is the size of the board. n ≤ 200. Each row in next n rows is a string contains only n lowercase characters, which describes the board. Output: Only 1 integer which is the maximum size of palindrome sub square in the board. Example: Input 1: 4 babb acaz babx fdhk Output 1: 3 Input 2: 1 a Output 2: 1
33,465
Digit Sum (PR003004) For a pair of integers a and b, the digit sum of the interval [a, b] is defined as the sum of all digits occurring in all numbers between (and including) a and b. For example, the digit sum of [28, 31] can be calculated as:                2+8  +  2+9  +  3+0  +  3+1 = 28 Given the numbers a and b, calculate the digit sum of [a, b]. Input On the first line one positive number: the number of test cases, at most 100. After that per test case: one line with two space-separated integers, a and b (0 ≤ a ≤ b ≤ 10 15 ). Output Per test case: one line with an integer: the digit sum of [a, b]; Example Input: 3 0 10 28 31 1234 56789 Output: 46 28 1128600
33,466
Yungom (HPREFIX) After getting her Ph.D in Cooking with her research paper on "How to Prepare a Pizza", and another Ph.D in Medicine for finding cures for H.I.V. and Alzheimer's, Dae Jang Guem (Called Yungom in Persian) decided to solve yet another open problem in Information Theory that even Shanon (the father of Information Theory) failed to solve. She is going to construct a language of n words with d given characters c1, c2 ... cd. This language should be prefix free which means that there is no pair of words like (s, t) in which the word s is a prefix of t. Each character ci has a usage cost of wi. The cost of a word s with the length l is the sum of the costs of its l characters. For example, if c1=a; c2=b; w1=1 and w2=10, the cost of word "aba" is 1+10+1=12. Similarly, the cost of a language with n words is equal to the sum of the costs of its n words. For example, the cost of language “ab”; “bbb”; “baaa” is 11+30+13=54. Like her previous jobs, Yungom is going to do this task perfectly which means that she wants to find the minimum cost, prefix free language with n words. Input There are multiple test cases in the input. Each test case starts with a line containing two integers n (1 ≤ n ≤ 200) and d (1 ≤ d ≤ 200). The next line contains non-negative integers w1, w2 ... wd. The input is terminated by a line containing two zero numbers. Output For each test case, you should print the minimum cost of a prefix free language with n words and d characters. Sample Input 3 4 1 10 100 1000 0 0 Output 23
33,467
Bank robbery (BANKROB) The city is plagued with bank robbers, and last year there was a robbery each week in some bank in the city. Police wants to fight this plague, and has to come up with a strategy to solve the problem. One obvious solution would be to place a police patrol at every bank, but this would cost too much money, and because of the crisis it is not possible to choose this solution. An alternative solution is as follows. Police is alerted about the robbery right after it happened, and can react pretty fast. Robbers use only either motors or cars. Police is able to block any crossroad in the city, and once a crossroad is blocked it is sure that the robbers will be caught if they try to pass the blockage. Moreover, it is possible to forecast some possible destinations of escape from a given bank. Thus the strategy in this case would be to, immediately after a robbery, block some crossroads to make it impossible to reach an escape destination. It would be also great if the number of blockages would be as small as possible, since then the action is cheaper, more effective, and less troublesome for the citizens. Obviously, if we would compute the smallest number of crossroads that make it impossible to pass from a given bank to given escape points, then this information would be actually useless for the police. Because of the geometry of the city, most likely the smallest set of blockages would consist of couple of crossroads right next to the bank, and by the time police would arrive there, the robbers would be already somewhere else. Thus during the chase, police wants to make real-time decisions that depend on the progress of the situation. To make smart decisions police needs an efficient computer program to compute blockages, and it is your task to write this program. Your program has to read the description of the city map and two locations s and t. It has to compute and return one number, the minimum number of blocked crossroads that will make it impossible to go from location s to location t. Input Your program reads from the standard input. In the first line of input you are given two natural numbers n and m (1 < n <= 1000, 1<= m <= 5000), where n is the number of crossroads in the city, and m is the number of streets, where each street connects two crossroads; any two crossroads can be connected by at most one street. Crossroads are numbered from 1 to n. In the line number 2 of the input you are given two numbers s and t, indicating the crossroads that have to be disconnected. In the next m lines of the input you will be given the description of the connections; each such line consists of two numbers c1, c2 and it means that there is a two-way street connecting crossroads c1 and c2. Output On the standard output your program has to write one number, the smallest number of crossroads that, when blocked, make it impossible to reach t from s. You may assume that there is no street directly connecting s and t. Example 1 Input: 10 14 1 10 1 2 1 3 1 4 2 5 3 5 3 6 4 6 5 7 5 8 6 8 6 9 7 10 8 10 9 10 Output: 2 Example 2 Input: 10 14 5 10 1 2 1 3 1 4 2 5 3 5 3 6 4 6 5 7 5 8 6 8 6 9 7 10 8 10 9 10 Output: 3
33,468
Alturas de NoMeAcuerdo (ALTURAS) In NoMeAcuerdo city a population census has been conducted last week. As a result, two lists (temporary data for a certain process) were generated: one list with the heights in cm. for the women of the city, and another list with heights in cm. for the men. The data in each list are not necessarily sorted, and contain a height for each woman or man. Input Lists should be read from the input in the order indicated above (first the women heights, then the men heights). Each list ends with a 0 indicating end of the list. It is known that each list will have no more than 500 elements. Output Your program should output four lines. The first line should be a list containing the two original lists merged and sorted, with only one occurrence of each value. The next 3 lines will show: number of women, number of men and number of different heights. Example Input: 155 180 165 165 172 166 170 172 180 0 173 150 180 199 168 168 170 165 167 155 0 Output: 150 155 165 166 167 168 170 172 173 180 199 9 10 11
33,469
Servers (SERVS) Suppose we want to replicate a file over a collection of n servers, labeled S 1 , S 2 ... S n . To place a copy of the file at server S i results in a placement cost of c i , for an integer c i > 0. Now, if a user requests the file from server S i , and no copy of the file is present at S i , then the servers S i + 1 , S i + 2 , S i + 3 ... are searched in order until a copy of the file is finally found, say at server S j , where j > i . This results in an access cost of j − i . (Note that the lower-indexed servers S i−1 , S i−2 , ... are not consulted in this search.) The access cost is 0 if S i holds a copy of the file. We will require that a copy of the file be placed at server S n , so that all such searches will terminate, at the latest, at S n . We’d like to place copies of the files at the servers so as to minimize the sum of placement and access costs. Formally, we say that a configuration is a choice, for each server S i with i = 1, 2 ... n −1, of whether to place a copy of the file at S i or not. (Recall that a copy is always placed at S n .) The total cost of a configuration is the sum of all placement costs for servers with a copy of the file, plus the sum of all access costs associated with all n servers. Write a program which reads from the standard input the placement costs and writes a single number, the minimum cost of a configuration. First line of the input consists of the number n of servers (1 ≤ n ≤ 1000). In the next n lines you are given the placement costs, in line i + 1 you are given the placement cost c i of server S i . Example Input: 4 1 1 1 9 Output: 12 Input: 4 4 3 2 1 Output: 6
33,470
Board (BOARD1) Consider a board with fields numbered from 0 to n . On each field i ∈ {1... n } there is an integer (possibly negative) number a i ∈ Z. A player is given a pawn on field number 0. Player can move the pawn back and front on distance not exceeding k . A pawn can visit all the fields many 0, and n many times, but it can stop moving definitively only at position n (player decides on when to stop). Whenever a pawn visits field i , the field is cleared and the number a i is removed (if the field wasn’t clear before the move). A player wants to maximize the sum of numbers on non-cleared fields. Write a program that reads on the standard input the description of a game, and writes on standard output the value of an optimal strategy. Input On the first line of input you are given the number n (1 ≤ n ≤ 1000). On the second line of input you are given the parameter k (1 ≤ k ≤ n ). In the next n − 1 lines of the input you are given single integer numbers, where on line i + 2 you are given the number a i . There are no values given for fields 0 and n , because these positions will be always clear at the end of the game. Output A single integer giving the required answer on a separate line for each test case. Example Input: 5 5 15 5 8 15 Output: 43 Input: 5 2 15 5 8 15 Output: 30
33,471
Operation Bits (OPBIT) Operation bits - A new operation conducted by the secret team currently working on a project on security enhancement. Mr. Abay, the team head, has found a new pattern on the perfect squares. This can be used as a outer cover for his project as its securing power is low. So he assign you this problem to find the key based on the given conditions: "An two adjacent perfect squares have their absolute difference as an odd number except when a and b are equal. Your task is to find the key which is defined as:  key(a, b) where a and b are perfect squares is ( ( AND( absolute difference between every adjacent perfect squares in [a, b]) ) AND ( XOR( absolute difference between every adjacent perfect squares in [a, b]) ) )" Find the key for the given inputs :) Input The input begins with a number T (1 ≤ T ≤ 1000) where T is the number of test cases. T lines follow Each line has two numbers a and b (0 < a ≤ b ≤ 10 6 ) It is assured that a and b are perfect squares. Output For each test case print the corresponding key. Example Input: 2 1 4 25 49 Output: 3 0 for test case 1 we have key=(3)&(3)=3
33,472
Guess The Number With Lies v3 (GUESSN3) GUESSN3 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 range R = [a, b]. The reply for query is "YES", if a ≤ x ≤ b. Otherwise the reply is "NO". 1 ≤ a ≤ b ≤ 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 a b. 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). Constraints 1 ≤ T ≤ 2 10 2 ≤ n ≤ 10 18 m: This value will be as small as possible. This means, that there exists strategy for player to find the value x using m queries, but there doesn't exist such strategy using m-1 queries. Example The example of communication. J=Judge, P=Player. J: 3 P: START_GAME J: 2 3 P: QUERY 1 1 J: YES P: QUERY 2 2 J: YES P: QUERY 1 1 J: NO P: ANSWER 2 P: START_GAME J: 2 3 P: QUERY 1 1 J: YES P: QUERY 2 2 J: NO P: ANSWER 1 P: START_GAME J: 5 6 P: QUERY 1 3 J: YES P: QUERY 4 5 J: YES P: QUERY 2 4 J: YES P: QUERY 3 4 J: NO P: ANSWER 2 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. 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. 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
33,473
Airplane Parking (HFLY) During this economic crisis time, Jack has started an incredible new business related to air travel, a parking-lot for airplane. He bought a very large land to park airplanes. However the land is very narrow, so that the only way airplanes can go in or go out of the parking lot must be in the Last-In First-Out fashion (see picture below). He only has spaces in the parking lot so he cannot take some airplane at the end out so that other airplanes can move. Because of the limitation of the parking lot, it is not possible to accommodate all requests for parking. Each request consists of the planned arrival time and planned departure time, which are the times the airplane arrives at the parking lot. An example below shows a request table for 4 planes. Airplane Arrival Departure 1 1 10 2 2 5 3 3 7 4 6 9 In this case, it is possible to accommodate airplane 1, 2, and 4. But it is not possible to accommodate both airplanes 2 and 3. It is possible that different planes plan to arrive or depart the parking lot at the same time. Jack has the best crews working with him, so that they will manage to arrange the plane to the parking lot in the best way that if it is possible to park and take out the planes they will be able to do it. Consider another example. Airplane Arrival Departure 5 10 12 6 10 15 7 13 17 Although airplane 5 and 6 arrive at the same time, Jack's crews know that airplane 5 will have to be out before airplane 6, so when both airplanes arrive they put airplane 6 in first, following by airplane 5. Given a list of parking requests, you want to find the maximum number of airplanes that can be parked in this parking lot, provided that they can only depart in the Last-In First-Out fashion. Input The first line contains an integer  T , the number of test cases (1 ≤ T ≤ 5). Each test case is in the following format. The first line starts with an integer  N  (1 ≤ N ≤ 300) denoting the number of airplanes. The next  N  lines describe the request table. Each line 1 +  i , for 1 ≤ i ≤ N , contains two integer  S i  and  T i , (0 ≤ S i  <  T i ≤ 1,000,000,000) which are the planned arrival time and planned departing time for airplane  i . Output For each test case, you program must output a single line consisting of one integer, the maximum number of airplanes that can be parked in Jack's parking lot. Example Input: 2 4 1 10 2 5 3 7 6 9 3 10 12 10 15 13 17 Output: 3 2
33,474
Bits Game (DCEPC12B) Pranjali and Nancy are playing an amazing game. The game starts with a string of bits (i.e. string of 0’s and 1’s). Game progresses in the form of right to left bit by bit scans. Pranjali takes turn when a “1” bit comes while scanning the string and Nancy takes turn when a “0” bit comes while scanning. In their respective turns, they can either choose to toggle their bit or keep it unchanged. The goal is to make all bits 0 at the end of scan, failing which means the scanning starts again from right to left. If all the bits are 0 at the end of a scan, the game ends and Pranjali is declared a winner. There is no win for Nancy. The game either ends to the goal described or the scanning continues indefinitely. So it can be seen that Pranjali has to win the game and in an optimal number of scans whereas Nancy’s aim is to not let Pranjali win (by making it an indefinite play) or to delay Pranjali’s win if it’s sure. So now assuming that they both play with their optimal strategy, can you please tell if Pranjali can win the game or not? Note: There has to be AT LEAST 1 scan before the game can end. Input First line contains T, the number of test cases. Each of the next T lines contains a string of 0’s and 1’s. Output For each string given in the input, output either “WIN m”, without quotes, if Pranjali can force her win in “m” scans in an optimal play, or output “INFINITE PLAY” if the game cannot be reached to the above mentioned goal in an optimal play. Constraints 1 ≤ T ≤ 20 1 ≤ Length of string ≤ 50 Example Input: 2 1 10 Output: WIN 1 WIN 2 Explanation In the 2 nd test case, during the first scan, Nancy gets the first turn because the right most bit is 0. She has to toggle it or the game will be over in a single scan. In the next turn, Pranjali chooses to keep her bit unchanged. So after first scan, the string is now “11”. In the next scan, Nancy has no turns. So Pranjali will toggle both 1 bit and thus end the game.
33,475
Dazzling Pearls (DCEPC12D) Nancy and Pranjali are best friends. For her birthday, Pranjali bought a beautiful bracelet for Nancy, made of ‘N’ multi-coloured pearls. Although stunned by the beauty of the pearls and touched by the gesture, Nancy felt that the arrangement of pearls could be changed somewhat, to make the bracelet even more beautiful. After thinking for a long time and making complex calculations, she came up with a formula to calculate the Elegance Factor (E) of the bracelet. Starting from a particular pearl, she numbers all the pearls from 0 to N-1. Next, she assigns a numeric value to each distinct colour of the pearls, based on RGB values. Thus the bracelet can be represented by a circular integer array ‘A’ of size N. Also she comes up with another array, ‘B’ also of size N. Now, the Elegance Factor is given by: E = sum (i = 1 to n-1) {(A [i] – A [i-1]) × B[i]} Obviously, Nancy wants to find an arrangement with the maximum value of E. If there are multiple such arrangements, then she wants the lexicographically smallest one. Once she has found the required arrangement, Nancy proceeds to re-arrange the pearls in the bracelet. However, Pranjali does not like the fact that her friend is making so many changes to her gift. To make her task much harder, she gives Nancy a number, D, and tells her that in 1 move, she can interchange the positions of 2 pearls only if they are at a distance D from each other. Nancy does not want to upset her friend, but she also wants to finish the rearrangement as fast as possible. Can you help her find the minimum number of moves to finish the re-arrangement? If it is not possible to reach the desired arrangement, output -1. Note 1: In case of multiple possible arrangements with the maximum elegance factor, the desired one is always the lexicographically smallest one, irrespective of whether it can be reached or not. Note 2: There can be at most 3 distinct colours of the pearls in the bracelet Note 3: Remember, the bracelet is circular. The distance D can be in both directions. Input First line contains T, the number of test cases. First line of each test case contains 2 space separated integers, N and D. The next line contains N space separated integers representing array A. The next line contains N space separated integers representing array B. Output Output a single integer, the minimum number of moves, or -1 if not possible. Constraints 1 ≤ T ≤ 5 2 ≤ N ≤ 14 1 ≤ D ≤ N-1 1 ≤ A[i] ≤ 1000000 0 ≤ B[i] ≤ 1000000 Example Input: 1 5 1 2 3 4 2 3 0 0 0 0 0 Output: 3 Explanation For all arrangements, E = 0. Therefore the desired arrangement is the lexicographically smallest one i.e. 2 2 3 3 4. The 3 pairs of indices to be exchanged (in order) to achieve this are (0 based indexing): 2 - 3; 3 - 4; 1 - 2;
33,476
End of Fun (DCEPC12E) Its holiday time after exams and Kappi and Pushap are enjoying to its fullest. But the sadist Sid, their teacher, can’t see them enjoy. Sad isn’t it? To ruin their fun, he gave them a programming problem to be solved within next 5 hours. He gives them 2 square matrices of equal dimension, Matrix A and a Matrix B and asks multiple queries on these matrices. The queries will be to change a particular element of one of the matrix and output the sum of elements of product of their matrix. Sid asks a lot of such queries. Kappi and Pushap don’t want the end of fun and so they ask you to solve this problem on behalf of them. Input First line consists of N, the dimension of matrix. Each of the next N lines contains N space separated integers. This is matrix A. Each of the next N lines contains N space separated integers. This is matrix B. Next line contains Q, the number of queries asked by Sid. Each of the next Q lines consists of queries of the form “A i j K” or “B i j K” (quotes for clarity), meaning change the element in ith row and jth column of matrix A or B to value K. Output Output exactly Q lines corresponding to Q queries, each containing the sum of the elements of the matrix A × B. Example Input: 2 1 2 3 4 4 3 2 1 3 A 1 1 2 B 0 1 3 A 0 0 10 Output: 40 40 103 Constraints 1 ≤ N ≤ 100 1 ≤ Q ≤ 100000 0 ≤ i, j < N -10 6 ≤ A[i][j], B[i][j] ≤ 10 6
33,477
Fitting in the Team (DCEPC12F) Aman, Gitanshu and Vishal have recently been selected as admins of DCE Coders. Kapish is pretty happy with the selection, but he wants to make sure that the new admins understand the importance of team-work if they are to take DCE Coders forward in the coming year. Keeping this in mind, he challenges the 3 of them to a game. Kapish takes all 3 of them to a long narrow corridor, and gives each of them separate start and end coordinates. The task is simple: All of them have to go from their start coordinates to their respective end coordinates simultaneously (i.e. using the same number of moves). However, they can only move in some discrete steps, which are also given by Kapish. He provides one array (of size ‘N’) of acceptable jumps to each of the 3. The challenge is that in one move, all 3 of them have to agree upon 1 common index (from 0 to N-1) and then they would add the value corresponding to that index from their respective arrays to get their new coordinates. Now Pushap, who likes challenges (such as jumping off moving trains!!), further complicates the problem. If the index selected in the previous move is odd, then it must be even for the current move, and vice versa. They can choose any index for the first move. The 3 new admins are required to find the minimum number of moves in which all 3 of them can simultaneously reach their destinations. Can you help them? Note 1: You can assume the corridor is 1 dimensional and infinite. Note 2: It is possible for more than 1 person to be on the same coordinate at the same time. Input First line of input contains T the number of test cases. First line of each test case contains 3 space-separated integers, A1, G1 and V1, the initial coordinates for the 3. Next line contains 3 space separated integers, A2, G2 and V2, the final coordinates for the 3. Next line contains a single integer, N. Next 3 lines contain N space-separated integers each, denoting arrays A, G and V of acceptable jumps for the 3. Output Output a single integer (in a separate line) per test case, containing the minimum number of moves. If it is not possible for them to reach their destinations simultaneously, output -1. Example Input: 1 1 2 3 2 3 5 2 1 3 1 2 2 1 Output: 1 Explanation The 3 of them can choose index 0 in the first move to reach their destinations. Constraints 1 ≤ T ≤ 5 -50 ≤ A1, A2, G1, G2, V1, V2 ≤ 50 1 ≤ N ≤ 20 -10 ≤ A[i], G[i], V[i] ≤ 10
33,478
G Force (DCEPC12G) Prime( n ) is defined as  number of primes less than equal to n . Totient( n ) is defined as the number of positive integers less than or equal to  n  that are relatively prime to  n . F( n ) = Prime( n ) – Totient( n )  and we don’t like negative values, so if F( n ) < 0, consider it as 0. G(n) = Totient( n ) (Factorial (F( n )))   You are given a number n . You have to output G( n ) % 10 9 +7. Input First line consists of T , the number of test cases. Each of the next T lines contains one integer n . Output Output T lines each line containing the value of function G( n ) % 10 9 +7 Constraints 1 ≤ T ≤ 100 1 ≤ n ≤ 10000000 Example Input: 1 2 Output: 1
33,479
Height of Expectation (DCEPC12H) Welcome To ICPC! ICPC is a programming competition in which N teams participate every year. Out of N teams, K number of teams has been selected from our college. You know what? K is always a prime number. Coincidence! Before going to ICPC, we want to calculate our expected overall score of our college. Expected Overall score is defined as expected median value of our college team’s ranks. All the ranks are distinct. Team’s rank value always lies between 1 to N. Input First line consists of T, the number of test cases. Each of the next T lines contains 2 space separated integers N and K. Output Output T lines each line containing expected overall score of our college. You should output at least 6 digits after decimal. Constraints 1 ≤ T ≤ 500 1 ≤ N ≤ 100 1 ≤ K ≤ 10 K ≤ N Example Input: 1 3 3 Output: 2.0000000
33,480
Joy of Arbitrage (DCEPC12J) Gitu is the smartest economist in the city. He has been kidnapped by Ankur and Vaibhav. They want him to make profit by Arbitrage. Arbitrage, roughly, is the process of taking advantage of price differences in various economies/markets to earn profit. So Ankur and Vaibhav have some units of each of the N valuables items to be sold in exactly N different markets in exchange of some money. Now they want Gitu to sell the items intelligently and maximize the total money earned. However, there is one condition. If Gitu sells some units of a particular item in a particular market, he cannot sell further units of that item in any other market and he cannot sell any other item’s units in this market. Ankur and Vaibhav have allowed Gitu to talk to you and only you. Can you help Gitu to strategize the sell to make maximum earning? Input First line consists of T, the number of test cases. Each test case starts with an integer N, the different items to be sold and the different markets present. Next line contains N space separated integers, the units of each of the items Ankur and Vaibhav have. Each of the next N lines consists of N space separated integers. jth integer in ith line signifies the money earned after selling one unit of jth item in ith market. Output Output T lines corresponding to each test case, the maximum money that can be earned by following the process stated above. Constraints 1 ≤ T ≤ 10 1 ≤ N ≤ 40 All other integers in input are positive and not greater than 100. Example Input: 1 3 1 2 3 1 1 1 2 2 2 3 3 3 Output: 14
33,481
Cheating a Boolean Tree (GCJ082A) For this problem we will consider a type of binary tree that we will call a boolean tree. In this tree, every row is completely filled, except possibly the last (deepest) row, and the nodes in the last row are as far to the left as possible. Additionally, every node in the tree will either have 0 or 2 children. What makes a boolean tree special is that each node has a boolean value associated with it, 1 or 0. In addition, each interior node has either an "AND" or an "OR" gate associated with it. The value of an "AND" gate node is given by the logical AND of its two children's values. The value of an "OR" gate likewise is given by the logical OR of its two children's values. The value of all of the leaf nodes will be given as input so that the value of all nodes can be calculated up the tree. The root of the tree is of particular interest to us. We would really like for the root to have the value V , either 1 or 0. Unfortunately, this may not be the value the root actually has. Luckily for us, we can cheat and change the type of gate for some of the nodes; we can change an AND gate to an OR gate or an OR gate to an AND gate. Given a description of a boolean tree and what gates can be changed, find the minimum number of gates that need to be changed to make the value of the root node V . If this is impossible, output "IMPOSSIBLE" (quotes for clarity). Input The first line of the input file contains the number of cases, N . N test cases follow. Each case begins with M and V . M represents the number of nodes in the tree and will be odd to ensure all nodes have 0 or 2 children. V is the desired value for the root node, 0 or 1. M lines follow describing each of the tree's nodes. The X th line will describe node X, starting with node 1 on the first line. The first ( M −1)/2 lines describe the interior nodes. Each line contains G and C , each being either 0 or 1. If G is 1 then the gate for this node is an AND gate, otherwise it is an OR gate. If C is 1 then the gate for this node is changeable, otherwise it is not. Interior node X has nodes 2X and 2X+1 as children. The next ( M +1)/2 lines describe the leaf nodes. Each line contains one value I , 0 or 1, the value of the leaf node. To help visualize, here is a picture of the tree in the first sample input. Output For each test case, you should output: Case # X : Y where X is the number of the test case and Y is the minimum number of gates that must be changed to make the output of the root node V , or "IMPOSSIBLE" (quotes for clarity) if this is impossible. Limits 1 < N ≤ 20 2 < M < 10000 Sample Input 2 9 1 1 0 1 1 1 1 0 0 1 0 1 0 1 5 0 1 1 0 0 1 1 0 Output Case #1: 1 Case #2: IMPOSSIBLE In case 1, we can change the gate on node 3 to an OR gate to achieve the desired result at the root. In case 2, only the root can be changed but changing it to an OR gate does not help.
33,482
Magical Bus Journey (MABJ) Townsville has a well developed bus system. Since most of the important buildings in town are located along the Main Street, almost all the buses pass through the street. All the stops along the Main Street, and there are very many of them, are numbered with numbers: 0, 1, 2 and so on. All the buses enter the Main Street at the stop numbered 0 and continue towards the higher numbered stops. For each bus line (which is also identified by a number), there is a schedule posted at stop 0 giving the minutes within an hour when a bus of this line leaves the stop. Rahul arrives at stop 0 at m minutes (0 <= m < 60) after the hour and takes the first bus that leaves stop 0 along the Main Street. If Rahul arrives at stop 0 the same minute when a bus leaves, Rahul manages to board the bus. He leaves the bus at the next stop and takes the next bus that arrives and continues to the next stop where he leaves. Rahul continues in this fashion until he reaches stop n, 0 < n < 10^9. Your task is to find by which bus will Rahul arrive at stop n? Input Input contains multiple cases. The first line of a case gives t, the number of bus lines, 0 < t < 30. The next t lines each contain a number of a bus line followed by a colon and then a list (separated by spaces) of minutes after a full hour when the bus of this line leaves stop 0. Each list of departure times is terminated by -1. No bus leaves stop 0 more than 20 times in an hour, no two buses leave station 0 at the same time, all the buses have the same speed and they never meet at a stop. A line with m and n then follows. The input ends with a line where t = 0. This line should not be processed.  Output For each case of input, output in a format shown below the number of the bus line by which Rahul arrives at stop n.  Example Input: 1 11: 10 20 30 -1 3 2 2 11: 10 20 30 -1 134: 16 25 35 45 58 -1 48 783 0 Output: Case 1: Rahul arrives at stop 2 by bus 11. Case 2: Rahul arrives at stop 783 by bus 134.
33,483
Run length encoding (RLE) Ram had to send large amount of data to his friend Vishnu. Since he was concerned about the time and the amount of data transfer it will take, he wanted to compress the data before he sent it. So he turns to you for help. You need to perform run length encoding on a given string. The encoding is as follows : 'consecutive character count' followed by '!' followed by the 'character'. Do not encode the characters unless they lead to compression ! Input Input consists of multiple lines of strings s, one string per line, with |s| ≤ 100000 (read the input till EOF) Output For each input string, output a single line printing the run length encoding of the input string Example Input: aabbbbbccccc aaaabbbbbbbbbbbbbbbccccc Output: aa5!b5!c 4!a15!b5!c
33,484
Cows Language (COWWORDS) Like all bovines, Farmer John's cows speak the peculiar 'Cow' language. Like so many languages, each word in this language comprises a sequence of upper and lowercase letters (A-Z and a-z). A word is valid if and only if each ordered pair of adjacent letters in the word is a valid pair. Farmer John, ever worried that his cows are plotting against him, recently tried to eavesdrop on their conversation. He overheard one word before the cows noticed his presence. The Cow language is spoken so quickly, and its sounds are so strange, that all that Farmer John was able to perceive was the total number of uppercase letters, U (1 <= U <= 250) and the total number of lowercase letters, L (1 <= L <= 250) in the word. Farmer John knows all P (1 <= P <= 200) valid ordered pairs of adjacent letters. He wishes to know how many different valid words are consistent with his limited data. However, since this number may be very large, he only needs the value modulo 97654321. Input Line 1: Three space-separated integers: U, L and P Lines 2..P+1: Two letters (each of which may be uppercase or lowercase), representing one valid ordered pair of adjacent letters in Cow. Output Line 1: A single integer, the number of valid words consistent with Farmer John's data mod 97654321. Sample Input: 2 2 7 AB ab BA ba Aa Bb bB Output: 7 Explanation The word Farmer John overheard had 2 uppercase and 2 lowercase letters. The valid pairs of adjacent letters are AB, ab, BA, ba, Aa, Bb and bB. The possible words are: AabB ABba abBA BAab BbBb bBAa bBbB
33,485
Two Game (TWOGAME) Alice started playing a new simple game. She starts with the pair of integers (1, 1) and then she may a) duplicate one of the numbers or b) subtract the smaller number from the bigger one. So the game may proceed as follows: she starts with (1, 1), then she moves to (2, 1), then to (4, 1), then to (4, 2), then to (8, 2), then to (6, 2), etc. She is now wondering if given an arbitrary pair of positive integers (A, B), will she be able to reach at this pair using the proceduce described above ? Input The first line contains a single positive integer T (T = 500), denoting the number of test cases to solve. Each test case consists of a single line containing two positive integers A, B (A, B = 10 18 ). Output For each test case print a single line with the character Y if it is possible for Alice to reach the given pair or N if it is impossible. Example Input: 3 6 2 5 1 3 3 Output: Y Y N
33,486
WHAT A CO-ACCIDENT (SYNC13C) Ramesh and Suresh get a box full of five stars on lottery each. Since both the boxes need not have the same number of chocolates, they decide to play a game. The winner gets to have both the boxes of chocolates. They play alternatively and Suresh starts the game. Given the number of chocolates in both the boxes, let them be c1 and c2, the player takes either c1 or c2 number of chocolates and divide the remaining box of chocolates to two boxes (these two boxes need not have the same number of chocolates). The player who cannot make such a move loses. Given the initial number of chocolates (c1 and c2) find the winner.Assume both the players play optimally. Input First line of input contains a number T (1 <= T <= 1000), the number of test cases. Then follows T lines each containing two space separated integers c1 and c2 (1 <= c1 <= c2 <= 10000). Output For each test case print " Ramesh " or " Suresh " depending on who is the winner. Example Input: 2 3 1 4 5 Output: Ramesh Suresh
33,487
Cooperation in geometry ! (GCOOP) Aang is fond of geometric figures, especially with equilateral triangles. He likes to know how well equilateral triangles cooperate with other figures. He initially takes an equilateral triangle of side t1. He also takes a square of side a, rectangle of dimensions l and b, another equilateral triangle of side t2 and a circle of radius r. He then takes turn and places each figure near the initial equilateral triangle of side t1. While placing nearer, he can place those figures in any orientation, any two edges of the two figures can be along same line but the figures cannot overlap. He now needs to find a cooperation value which is the minimum area of the rectangle needed to surround the area of the two figures. For example, when he places a square near a triangle, the cooperation value is the area of the smallest rectangle which can surround the areas of the triangle and square. Now, given the values, find the cooperation values of all the figures with the initial equilateral triangle. Input First line consists of t, the number of test cases (1 <= t <= 20) Next t lines consists of 6 values t1, a, l, b, t2 and r denoting side of first triangle, side of square, length and breadth of rectangle, side of second triangle and radius of circle. (all values will lie between 1 and 100 inclusive) Output For each test case, print a single line consisting of the cooperation values of the first triangle with the square, rectangle, circle and the other triangle respectively. (separated by spaces rounded off to 4 decimal digits) Example Input: 1 2 2 2 3 2 1 Output: 7.4641 9.4641 7.4641 5.1962
33,488
Eat all the brownies ! (CUTCAKE) BrownieDude was given the job of cutting cake at a party for serving the guests. But BrownieDude is both lazy and hungry, so he wants to cut the cake into maximum number of pieces with minimum number of cuts and go off to eating brownies. The host of the party says that BrownieDude can cut the cake into unequal pieces but cannot cut in more than one plane. (Only vertical cuts are allowed.) Given the number of guests, find the number of cuts sufficient to generate the cake pieces. Input First line contains 't', the number of test cases. 't' lines follow. (1 ≤ t ≤ 1000) Each line denotes the number of guests. (1 ≤ n ≤ 10 11 ) Output One number denoting the number of cuts. Note: It is guaranteed that an integer solution will always exist. Example Input: 2 1 2 Output: 0 1 Explanation for test cases: If there is only one guest, there is no need to cut the cake. If there are 2 guests, the cake can be cut into 2 pieces in 1 cut.
33,489
Family members (FAMWEALT) Consider a family in the form of a binary tree consisting of male and female nodes. All the left nodes will be male nodes and all the right nodes will be female nodes. Root node will be female node. The root female initially has a wealth w which she passes on down the tree. The rules are as follows: all the males in the family pass half of their wealth to each of their children. all the female nodes pass only half of their wealth to both their children collectively, but the male child suddenly converts it to twice the wealth received. The members are numbered from 1 to n in the row-wise order. i.e., root will be 1, the two children will be 2 and 3 and so on. Given wealth W of xth node, you need to find the wealth of yth node. Input First line consists of t, the number of test cases (1 ≤ t ≤ 20). Each of t lines consists of three integer values x, y and W (1 ≤ x, y ≤ 10 6 and 1 ≤ W ≤ 1000). Output For each input test case, print the wealth of yth node in a single line (rounded off to six decimal digits.) Example Input: 2 11 3 1 4 6 4 Output: 4.000000 2.000000
33,490
The Bridge to Home (WAYHOME) Late in the night, a group of people are approaching home after an exciting adventure in the wilderness. However, as a last challenge on their long and tiresome fare, they have to cross a small bridge over a raging river. The bridge is so narrow and slippery that the group decides only to let a maximum of two people walk on it at any given time. Also, the person or pair who is walking on the bridge, must carry the single light that the group possesses. The group asks you to determine, given the amounts of time that each person takes to cross the bridge, the minimum total amount of time it'll take the entire group to cross. Notice that, when two people walk on the bridge at the same time, their crossing time is determined by the slower walker. Input First line: The number of test cases C . Next C lines: The number of people in the group N , followed by N sorted integers A i . A i is the crossing time of the i-th person. 0 ≤ C ≤ 100; 1 ≤ N ≤ 1000; 0 ≤ A i ≤ 1000. Output For each testcase, write the minimum total amount of time it'll take the group to pass. Example Input: 4 1 1 2 1 2 3 1 1 1 4 1 2 4 8 Output: 1 2 3 15 In the third test case, the people can cross the bridge in the following way: The first two people walk over the bridge, taking 1 time unit. One person walks back over the bridge, with the light, taking 1 time unit. The two people, now on the left, cross the bridge, taking 1 time unit.
33,491
Gopu and Combinatorics on Graphs (SPCE) Little Gopu was playing with graphs. He encountered following problem while playing. Given a graph G with n vertices and m edges. Let us say it has k connected components. Find out how many numbers of ways you can add k - 1 edges to make the graph connected. Note that the new edge you are going to add should not be a repeated edge i.e. if you are going to connect u, v then there should not be an edge between u, v already in the graph. Output the answer modulo 10^9 + 7. If the graph is already connected, Output -1 Help Gopu with this task. Input First line contains T : number of test cases. (1 <= T <= 20) For each test case, First line contains two space separated integers n, m: (1 <= n, m <= 10^5). Then For each of the next m lines, each line contains two space separated integers u and v denoting that u and v are connected to each other. (1 <= u, v <= n and u != v)   Output For each test case, output the answer as required. Example Input: 4 4 2 1 2 3 4 5 3 1 2 3 4 4 5 3 3 1 2 2 3 3 1 7 5 1 2 3 4 4 5 3 5 6 7 Output: 4 6 -1 84
33,492
Constructible Regular Polygons (POLCONST) The investigation of which regular polygons can be constructed only with compass and straight-edge is a classical problem in mathematics. Triangle, square, hexagon can easily be constructed, but, can we construct a regular heptagon? It was the German mathematician Gauss (1777-1855) who first proved that one could construct a 17-sided regular polygon and later, in one the of the most beautiful math works of all time ( Disquisitiones Arithmeticae , 1798), he gave sufficient conditions to decide which regular polygons can be constructed. Input In the first line, an integer T < 50000 representing the number of test cases; then, T integer numbers representing the number of sides of a non-degenerated regular polygon, up to 1000000 (10 6 ). Output Print “Yes” if the regular polygon can be constructed with compass and straight-edge or “No” otherwise. Example Input: 5 5 6 7 8 9 Output: Yes Yes No Yes No
33,493
Gopu and Create Collections Part Two (SPCJ) Little Gopu likes to play very much. As you know he only plays with numbers. So he is given n numbers. Now he tries to group the numbers into collections where each collection contains exactly two numbers. He can form the collection of two numbers a and b (a ≤ b), if and only if b is either 2 × a or 2 × a + 1. Note that you can not use a single number in forming of more than one collections. Eg. 1, 2, 4 He can divide the numbers into a single collection only either [1, 2] or [2, 4] because each collection requires exactly two numbers, and each number has to be used only once in a group. Given n numbers, Find out how many maximum number of collections he can form ? Input T: number of test cases. For each test case, First line will contain n:  (1 ≤ n ≤ 10 5 ) Then next line will contain n numbers single space separated. Range of each number will be between 1 and 10 18 . Sum of n over all the tests will be at most 10 6 . So number of test cases are decided on this criteria. Output For each test case, output maximum number of collections that can be formed. Example Input: 4 2 1 2 3 1 2 4 4 1 2 4 8 2 4 4  Output: 1 1 2 0
33,494
Gopu and function (SPCM) Once Gopu was reading a maths problem which had a weird looking function f as follows.                 {                          1, if n is a prime number. f(n)  =                 f (sum of prime divisors of n) + number of distinct prime divisors of n,  otherwise.                 } Compute f (n) for a given value of n.  Input First line contains T : number of test cases. (1 <= T <= 20) For each test case, there is a single line containing integer n. (2 <= n <= 10^12). Output For each test case, output value of f (n) in a single line. Example Input: 6 2 3 4 5 20 123456  Output: 1 1 2 1 3 6
33,495
Gopu and Counting Bitwise Prime Numbers (SPCO) A positive integer is said to be bitwise prime if the sum of all the bits in its binary representation is a prime number.  You are given two integers a and b. You have to output number of bitwise prime numbers between a and b (inclusive). Input First line contains T : number of test cases. (1 ≤ T ≤ 10 5 ) For next T lines, each test case contains two space separated integers a and b. (a ≤ b). 1 ≤ a, b ≤ 10 19 . Output For each test case, print the number of bitwise prime numbers between a and b (inclusive). Example Input: 2 1 2 1 3 Output: 0 1
33,496
Bad XOR (BADXOR) You are given an array A of N elements. Also you are given another array B of M elements. Any subset (i­ 1 , i 2 , i 3 ... i p ) is bad IFF (Ai 1 ⊕ Ai 2 ⊕ ... ⊕ Ai p ) equals any value of B. (⊕ means Bitwise XOR, which can be found with ^ syntax in popular programming languages.) Now your job is to find the number of good subsets. Empty subset has XOR value of 0. Input The first line of input denotes the number of test cases T (1 ≤ T ≤ 20). The first line of each test case contains two integers N and M (0 ≤ N, M ≤ 1000). The next line contains N integers of the array A (0 ≤ A i ≤ 1000). The next line contains M integers of the array B (0 ≤ B i ≤ 1000). You can assume that each element of array B will be unique. Output For each case, print the case number and the total numbers of good subsets in a line. As the result can be very big, output it modulo 100000007. Example Input: 2 2 3 1 2 0 1 2 1 3 1 0 1 2 Output: Case 1: 1 Case 2: 0 Problem Setter: Nafis Sadique, Special Thanks: Ahmad Faiyaz
33,497
Maximum Radius (MAXRAD) You will be given some 2D points. You need to draw circles with each point considering as a center of a circle with minimum radius 1 . And no two drawn circles should intersect with each other or contain each other. Now you have to find the maximum radius any circle can have so that all the circles have radius greater or equal to 1 and no two circles intersect with each other or contain each other. You have to print the maximum radius. If it is not possible to maintain the restriction for any radius, then you should print -1.000000 . Input Input starts with an integer  T (≤ 50) , denoting the number of test cases. Each case starts with a line containing an integer  N (2 ≤ N ≤ 1000)  denoting the number of 2D points. Each of the next  N  lines contains two integers  x i  y i   (-10 4  ≤ x i , y i  ≤ 10 4 )  denoting the co-ordinate of a point. These points may not be distinct. Output For each case, print the maximum radius a circle can have. If it is not possible to maintain the restriction then you should print -1.000000 . Errors less than  10 -6  will be ignored. Input: 2 2 1 1 3 1 2 1 1 2 1 Output 1.000000 -1.000000 Problem Setter: Ahmad Faiyaz Special Thanks: Aninda Majumder
33,498
Buying Integers (BUYINT) Let's assume that you have n integers, A 1 , A 2 , A 3 ... A n . Let's define: E = Number of pairs (i, j) such that i < j and (A i + A j ) are even. O = Number of pairs (i, j) such that i < j and (A i + A j ) are odd. D = | E-O | (That means, D = (E-O) if (E-O) ≥ 0, -(E-O) otherwise.) Unfortunately, you do have n but those n integers are lost. You will have to buy them again. Before going to the market, you have decided that you will buy n integers in such a way that the value of D will be as small as possible, as you will have to pay D golden coins to buy them. Now, you are wondering, what that minimum D will be. (Let's call it D min ). Input First line of the input file will contain the number of test cases, T ≤ 1000000 , followed by T lines, each containing an integer n ( 1 ≤ n ≤ 10 9 ). Output For each case, print the case number starting from 1 and D min for the value of n in that particular case. See the sample output for exact formatting. Example Input: 3 3 4 5 Output: Case 1: 1 Case 2: 0 Case 3: 2 Warning : Input file is huge, please use faster input and output methods (e.g. printf and scanf in C++). Problem Setter: Momontho Mashak Monmoy Special Thanks: Muhammad Ridowan
33,499