task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Strange Waca (NPC2016C) Waca loves maths,.. a lot. He always think that 1 is an unique number. After playing in hours, Waca suddenly realize that every integer can be represented by digit '1', plus operator and minus operator. For example, 1534 can be represented as 1111 + 1 + 111 + 111 - 11 - 11 + 111 + 111. In that case, there are total 7 operators (plus and minus). Now, Waca wants to know, what is the minimum number of operators needed to achieve X Input First row is an integer T, the number of test cases. Next T rows will each contain an integer, X, the number given to Waca Output For each test cases, print an integer, the minimum number of operators needed to achieve X. Example Input: 2 1534 219 Output: 7 4 Constraints: 1 ≤ T ≤ 10 1 ≤ X ≤ 10 12
34,200
Quest Hunter (NPC2016E) Tatama Land is on a crisis. Recently, a dragon woke up and will destroy Tatama Land to ashes. Hearing this news, Pheo, Waca, and Wembo decided to create a guild called Quest Hunter to slay the dragon. In order to defeat the dragon, they want to buy weapons first. They visit J0I Blacksmith, which sells N weapons, each with a price of X i gold. As Quest Hunter only have Y golds, they want to buy as many weapons as they can using Y golds. After buying weapons, they go to a local tavern to hire mercenaries for their guild. Each mercenary should buy a weapon they just bought. However, Quest Hunter lost the bill, and they totally forget how much gold for each weapon. They decided to randomly give a price to each weapon, but no weapon will costs 0 gold, and the total price of all weapons should be the same amount with total gold used to buy those weapons. Now, they're curious about how many price configurations available. As the answer can be very large, output it with modulo 10 9 + 7 Input An integer T, number of test cases in the first row For each testcase: - First row is an integer N - Second row contains N integer, X i , the price of each weapon - Third row is an integer Y  Output For each testcase, output "Case #C: D" where C is the testcase number and D is the number of configurations. Example Input: 2 5 1 2 3 4 5 6 4 2 2 2 2 1 Output: Case #1: 3 Case #2: 0  Explanation For the first case, total amount of money is (1+2+3) = 6 and there are 3 weapons. Quest Hunter can sell it using these configurations (1,1,4), (1,2,3), (2,2,2) For second case, Quest Hunter can't buy any weapons Constraints: 1 ≤ T ≤ 10 2 1 ≤ N,Y,X i ≤ 10 3
34,201
Prime is fun (ARRPRM) You will be given an array A. You can pick X (where X is a prime ) consecutive elements from the array A so that the sum is maximized. Note that you can select multiple consecutive elements. For example, if you are given an array with 10 elements, then one of ways you can select elements by selecting 1 st , 2 nd element then 4 th , 5 th , 6 th element then 8 th , 9 th elements. Another way can be to select 1 st and 2 nd element then select 4-10 elements. Input The first line of the input will be an integer t, denoting the number of the test cases. For each test case, there will be an integer n , denoting the size of the array A. Next line there will be n integers denoting the elements of the array A. Output For each test case, print the maximized sum (as discussed above) in a line. Constraints 1 ≤ t ≤ 100 1 ≤ n ≤ 2000 1 ≤ elements of the array A ≤ 100000 Sample Input: 2 4 1 2 3 4 10 10 1 1 1 1 1 1 2 2 2 Output: 9 21
34,202
Easy GCD (GCDEASY) We call a sequence of n non-negative integers A , awesome if there exists some positive integers x > 1 such that each element Ai in A (where 0 ≤ i < n ) is evenly divisible by x . Recall that a evenly divides b if there exists some integer c such that b = a * c . Given an awesome sequence, A and a positive integer k , find and print the maximum integer L , which satisfies the following conditions: 0 ≤ L ≤ K A ∪ {L} is also awesome. ( ∪ is the union operator.) Input The first line contains the integer t denoting the number of test cases. The next line contains two space-separated positive integers, n (length of the sequence A ) and k (the upper bound of answer L ). The third line contains n space separated positive integers describing the elements of A . Output For each test case, Print the value of L in a single line (where L is the maximum integer ≤ k and A ∪ {L} is also awesome). As 0 is evenly divisible by any x > 1 , there will always be an answer. Constraints 1 ≤ t ≤ 12 1 ≤ n ≤ 100000 1 ≤ k ≤ 1000000000 1 ≤ Ai ≤ 1000000000 Example Input: 2 3 5 2 6 4 1 5 7 Output: 4 0
34,203
Moumita and Assignments (MAS) Moumita doesn’t like assignments. Whenever she is given any assignment, she feels helpless and wants to destroy the world. Unfortunately, she has a pending assignment. As she doesn’t know how to do it, she is preparing to destroy everything. Can you help her to complete it and save the world??? The assignment is, you are given an array A of n elements and a function F(A) which is defined as: where mod = 2,760,727,302,517 You have to perform Q queries of the following types: 1 x v (which means set A[x] = v.) 2 x v (which means add v to A[x] i.e., A[x] = A[x]+v.) 3 (which means compute F(A) and output it in a single line.) Input Input starts with an integer T denoting the number of test cases. The first line of each case contains two integers n and Q. The next line contains n space separated integers, where i th integer denotes the value of A[i]. Each of next Q lines contains a query of the above specified types. Constraints 1 ≤ T ≤ 6 1 ≤ x ≤ n ≤ 100000 1 ≤ Q ≤ 100000 0 ≤ A[i], v ≤ 1000000000 Output For each case, print the case number first. Then for each query of type 3, print the value of F(A) in each line. See sample I/O for more clarification. Example Input: 1 3 5 1 2 3 3 1 1 5 3 2 3 6 3 Output: Case 1: 6 14 74
34,204
Luke vs. Darth Vader (LVADER) You know one of the most dangerous villain of all time, it's Darth Vader. It's time to stop him and Master Luke is looking forward to fight against him. They both are in an infinite two-dimensional grid. Each cell is denoted by (x, y). Here x denotes the row number and y denotes the column number of that cell. Please have a look on that picture of 5 * 7 grid to understand. 0, 0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6 1, 0 2, 0 3, 0 4, 0 Luke stays at a cell (x1, y1) and Vader stays at another cell (x2, y2). It is guaranteed that x1 <= x2 and y1 <= y2. Master Luke needs to reach Vader’s cell. Each time Luke can move one step below horizontally or vertically or diagonally. That means, if his position is (x, y) then he can move to (x+1, y) or (x, y+1) or (x+1, y+1) cell in a single move. Given Luke and Vader’s position you have to determine in how many ways Luke can reach to the Vader’s cell. As the answer can be very large output the solution modulo 10^9 + 7. Input Input starts with an integer (T <= 50) which denotes the number of test case. Each test case consists four integer x1, y1, x2, y2 (0 <= x1 <= x2 <= 100000 and 0 <= y1 <= y2 <= 100000), the position of Luke and Vader. Output For each test case, print the number of ways Luke can reach to the Vader’s cell modulo 10^9 + 7. Example Input: 3 1 2 2 3 2 2 3 3 3 4 3 5 Output: Case 1: 3 Case 2: 3 Case 3: 1 Explanation In the first case he can move from (1, 2) to (2, 3) in the following 3 ways: (1, 2) → (1, 3) → (2, 3) (1, 2) → (2, 2) → (2, 3) (1, 2) → (2, 3)
34,205
TWO STRINGS (HARSTR) You are given two strings  a  and  b . You have to remove the minimum possible number of  consecutive  (standing one after another) characters from string  b  in such a way that it becomes a  submultiset of string  a . It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from  b  and make it empty. Input The first line contains string  a , and the second line contains string  b . Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 10 5  characters. Output On the first line output a submultiset of string  a in sorted order, obtained from  b . If multiple answers exist, output lexicographically smallest . If the answer consists of zero characters, output "-" (a minus sign). Example Input: abacaba abcdcba Output: aabbc Input: abcdy abdxybc Output: abcd Note: ouput is abcd not abcy since abcd is lexicographically smaller.
34,206
THE HONEYCOMB MAZE (ALCATRAZ3) You won the lottery tickets to visit the famous Disneyland Hong Kong with the Taarak Mehta ka Ulta Chasma family and Subramaniam Iyer gets stuck in the Honey Comb maze. He has a Phone along with him and no one else to help him out. He calls you and asks for help. Chuck the story getting into the problem now, There are N x M blocks of Honey combs in the maze and you are given a starting point. your task is to help Mr. Iyer find out whether or not he can traverse the maze and return to his original position. The constraint being that a honey comb (Block) once visited cannot be visited again. Also, he has to make a minimum of 'k' number of moves before returning to the starting point. The '.' represent the empty blocks whereas the '*' represent the blocks that can't be visited. from a block (x,y) Iyer can move only to blocks (x-1,y), (x+1,y), (x,y+1), (x,y-1). Help Mr. Iyer return to his original position. Input The first line of the input contains the dimensions of the maze (N x M). Second line of the input contains 'k' as described above. The third line denotes the coordinates of the starting point (1-n), (1-m). The next N lines contain the description of the Nth row. Output Output "YES" if it's possible. Else output "NO". Constraints 1 <= N, M <= 100 Example Input: 5 5 14 1 2 ...** *...* *.... .*... .*..* Output: YES Explanation 1,2 → 2,2 → 3,2 → 3,3 → 4,3 → 5,3 → 5,4 → 4,4 → 4,5 → 3,5 → 3,4 → 2,4 → 2,3 → 1,3 → 1,2 14 moves were made. So, it is possible. Also, no blocks were repeated.
34,207
Ada and Trip (ADATRIP) Ada the Ladybug loves trips. She travels around world taking photos and souvenirs. This week she went to Buganda. Common Tourist would surely travel around main city and some conurbations, but Ada has different politics. She wants to go as far as possible (because photos from outlying places are much more valuable). Problem is, that Buganda is very large so she can barely guess such places. Luckily, you are around so she asked you for help. Can you tell her, how far and how many cities are most distant (if the shortest path is used)? Input The first line will contain three integers 1 ≤ N ≤ 5×10 5 , 0 ≤ M ≤ 10 6 , Q , the number of cities in Buganda, the number of roads and number of queries (possible arrival cities). Then M lines follow, with three integers 0 ≤ A, B < N, 0 ≤ L ≤ 10 , A, B are cities, which the (bidirectional) road connects and L is length of the road. Afterward, Q lines follow, each with number 0 ≤ q i < N , meaning the city of arrival. You are assured that max(N, M)×Q will be always lesser/equal than 10 7 Gentle warning : Since we are in real world and not in some "graph theory", multiedges and self-edges are completely valid! Output For each query print two numbers: The distance of most distant place(s) and number of such places. Example Input 10 10 10 1 1 1 1 2 1 1 2 3 3 1 1 5 4 10 8 5 10 5 6 5 6 7 3 6 9 3 9 7 4 0 1 2 3 4 5 6 7 8 9 Example Output 0 1 1 2 2 1 2 1 20 1 10 2 15 2 18 2 20 1 18 2 Most distant cities (explanation) 0 2 3 3 2 8 4 8 4 8 4 8 4 4 8
34,208
Ada and Nucleobase (ADAMATCH) Ada the Ladybug is helping her friend who is biologist. He examines DNA. Actually he has a long DNA of one bug, consisting of adenine, cytosine, guanine and thymine and he wants to know whether another bug might be relative to first bug. A bug is relative to another bug if his his DNA has very low Hamming Distance with some substring of the first bug. Your job is to find the lowest hamming distance between second DNA and any substring of first DNA. Input Input contains only two lines: first DNA ( s ) and second DNA ( r ). It is true that 0 < |r| ≤ |s| ≤ 5*10 5 |s| means length of string s . All strings contains only A, C, T, and G . Output Print minimal Hamming Distance (the number of mismatched nucleobases) of any substring of s and r (the substring MUST have length |r| ) Example Inputs ACTGACTGACTG ACCG AAAAAACCA AAACA ACGC GGG ACTTTG TTTGA ACTGACTGACTG ACTG Example Output 1 1 2 3 0 Inputs explanation ACTG ACTGACTG AAAA AACCA A CGC A CTTTG ACTG ACTG ACTG
34,209
Ada and Diary (ADAHACK) Ada the Ladybug's crush Bumblebee Blazewan has a secret diary. Ada wants to read it to see, whether he loves her too. Sadly, the diary is locked with some very strong cipher so she can't read it. She asked you for help. Unfortunately, you are not able to break through. Yet you observed, that the key generated in the cipher is generated in following way X i+1 =(aX i +b) mod (10 11 +3) . You was able to find out first six X i 's. Predicting next will help you to get through - can you do it? Input There will be no more than 10 5 test-cases. Each test-case consists of line containing 6 integers 0 ≤ X i < 10 11 +3 ( 1 ≤ i ≤ 6 ) Output For each test-case print X 7 (modulo 100000000003). Example Input 2 10 34 106 322 970 2 4 4 4 4 4 2 11 47 191 767 3071 0 0 0 0 0 0 2 8 32 128 512 2048 Example Output 2914 4 12287 0 8192 Possible setting a=3, b=4, X 1 =2 a=0, b=4, X 1 =2 a=4, b=3, X 1 =2 a=2, b=0, X 1 =0 a=4, b=0, X 1 =2
34,210
Ada and Rain II (ADARAINB) As you might already know , Ada the Ladybug is growing plants. She used to have a very long furrow, yet it costs a fortune to fence it. To reduce it, she has decided to build a square field. It is so big, that most of water falling from rains drops just onto a rectangular part of the field. Ada doesn't want the plants to wither, so she records all rains to know, how much water every particular plant got. Sadly, there are so many rains that she couldn't handle this alone! At first, you will be given N queries with [x, y], [X, Y] rectangles telling you, where all of the N rains has fallen (lower left / upper right corners of it). Afterward M queries follow, with number i - the i-th plant for which you want to know, the number of rains, which has fallen onto it. Input The first line will contain 0< N, M ≤ 3×10 5 , 0< L ≤ 5000 , number of rains, number of questions and size of square field. Then N lines follow, each containing four integers x, y, X, Y ( 1 ≤ x ≤ X ≤ L, 1 ≤ y ≤ Y ≤ L ), bottom-left and upper-right corner of rectangle where i th rain has fallen. Afterward M lines follow, each containing two numbers 1 ≤ x, y ≤ L , asking for number of rains which has fallen onto plant on coordinates [x, y] Output Print M lines (for each query of second type), with integer indicating number of rains, which has fallen onto the plant in query. Example Input 6 16 4 1 1 3 4 1 1 3 3 2 2 2 2 4 2 4 3 3 3 4 4 1 2 2 4 1 1 1 2 1 3 1 4 2 1 2 2 2 3 2 4 3 1 3 2 3 3 3 4 4 1 4 2 4 3 4 4 Example Output 2 3 3 2 2 4 3 2 2 2 3 2 0 1 2 1
34,211
Ada and Orange Tree (ADAORANG) Ada the Ladybug lives near an orange tree. Instead of reading books, she investigates the oranges. The oranges on orange tree can be in up to 5*50 Shades of Orange. She walks from orange to orange, examining different properties of orange tree. The oranges are connected by branches. There are more oranges then branches, yet it is still possible to get from any orange to any other orange [through branches]. The tree is rooted. Ada has many questions in following form: She goes from orange A to orange B (by shortest path) and is interested in total number different Shades of Orange among all subtrees of all edges on shortest path. Input The first line of input consists of 1 ≤ T ≤ 100 , the number of test-cases. The first line of each test case contains three integers 1 ≤ N, Q ≤ 4.5*10 5 , 0 ≤ R < N , the number of oranges, the number of questions and number of root. Next line contains N integers 1 ≤ S i ≤ 250 , the shade of orange of orange i . Next N-1 lines contains two integers 0 ≤ I, J < N, I ≠ J , the numbers of oranges which are connected by branch. Next Q lines contains two integers 0 ≤ A, B < N , the path Ada is interested about. The sum of all N and all Q among all test-cases won't exceed 10 6 Output For each question answer the number of shades in all subtrees of all nodes on shortest path from A to B . Example Input 1 10 7 1 1 2 1 4 5 6 6 8 9 9 0 9 9 3 3 4 4 6 4 5 4 8 1 3 1 2 2 7 4 4 8 6 0 6 7 0 7 2 0 0 2 3 Example Output 3 3 5 7 2 1 7 Explanation - shades in subtrees 5 6 9 5 6 9 1 4 5 6 9 1 2 4 5 6 8 9 1 8 1 1 2 4 5 6 8 9
34,212
Ada and Island (ADASEA) Ada the Ladybug just read a book from famous author Dobsonfly Daffoedil. It is about Robinson's Cicada, who was flying over sea. Suddenly she had an accident and fell to island below her. Luckily the island was big enough, so she could recover and fly home till Friday night... or something like that. As Ada was reading through the book, she fell asleep and started dreaming. She was thinking about how lucky the Cicada was, that she fell into such big island. She could have fallen into a smaller one or even to sea. It keeps bugging her, so she has asked you to tell her the expected size of island, the Cicada will fall to (considering equal probability for all coordinates). Since Ada is not friend of floating point numbers, she wants the answer in some "nice" form. Island is considered to be union of any '#' characters, which share side. Input The first line contains an integer T , the number of test-cases. Each test-case begins with two integers N, M , 1 ≤ N, M ≤ 1000 Afterward N lines follow, with M characters. Each of the characters is either ' # ' (island) or ' ~ ' (sea). Output For each test-case print the expected size of island. Output it as p / q , where p and q has no common divisor. If p / q can be printed as an integer (not as fraction), do so! Example Input 5 3 4 ~~~~ ~~~~ ~~~~ 3 3 #~~ ##~ ~~~ 4 5 #~##~ #~~~# ~~~~# ####~ 1 1 # 4 4 ~~~~ ##~~ ~##~ ##~~ Example Output 0 1 7 / 5 1 9 / 4
34,213
Ada and Homework (ADAHW) Ada the Ladybug came home with difficult homework. Since she is very skilled mathematician, she already deduced, how to count the answer for N. Consider all numbers K (in range 2 ≤ K ≤ N ), for which it is true that gcd(N,K)==1 and add gcd(N,K-1) to sum. What is the sum? A little bit more formally, find: ∑ gcd(K-1,N), for K ∈ [2,N] where gcd(N,K)==1 Anyway the numbers are too large, so she can't do that without your help. Can you help her? Input The first line contains 1 ≤ T ≤ 1000 , number of test-cases. Each of following T lines contains 2 ≤ N ≤ 10 18 , number for which Ada wants the answer. Output For each test case, print the sum of deduced formula. Example Input 11 2 5 6 7 8 10 50 100 1000 524288 945406969379503350 Example Output 0 3 2 5 8 6 70 260 5400 4718592 1381966975399059833610
34,214
Ada and Coins (ADACOINS) Ada the Ladybug has several coins in her wallet. She is wondering, how many different values [sum of some subset of coins] is she able to make (in given range). Input The first line contains two integer numbers 1 ≤ N ≤ 10 4 , 1 ≤ Q ≤ 5*10 5 , the number of coins and number of queries. The next line contains N integer numbers 1 ≤ A i ≤ 10 5 , the values of coins in Ada's wallet. Afterward, Q lines follow, each containing two integers 1 ≤ B ≤ E ≤ 10 5 , b eginning and e nd of range, for which Ada wants to know the answer Output For each query, output the number of distinct values Ada can generate in given range. Example Input 10 10 1 2 2 3 5 30 31 90 100 100 1 1 1 5 3 6 2 9 30 100 1 10000 30 32 5 12 9 29 190 220 Example Output 1 5 4 8 40 231 3 8 5 25 Output Subsets [ 1, 1]: 1 [ 1, 5]: 1 2 3 4 5 [ 3, 6]: 3 4 5 6 [ 2, 9]: 2 3 4 5 6 7 8 9 [ 30, 100]: 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 61 62 63 64 65 66 67 68 69 70 71 72 73 74 90 91 92 93 94 95 96 97 98 99 100 [ 1,10000]: 1 2 3 4 5 6 7 8 9 10 11 12 13 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 61 62 63 64 65 66 67 68 69 70 71 72 73 74 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 290 291 292 293 294 295 296 297 298 299 300 301 302 303 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 351 352 353 354 355 356 357 358 359 360 361 362 363 364 [ 30, 32]: 30 31 32 [ 5, 12]: 5 6 7 8 9 10 11 12 [ 9, 29]: 9 10 11 12 13 [190, 220]: 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 220
34,215
Ada and Manure (ADADUNG) As you might know Ada the Ladybug is farmer. Last year, she sowed N distinct types of grain to N distinct places. This year she wants to seed the same types of grain again, yet there is a little problem: each type of grain needs special kind of manure, yet fertilizing soil with same kind of manure in consecutive years might destroy it. Now she is asking you to count the number of ways, to seed N types of grain to N places in such way that no type of grain will be in its original place. Since this number might be pretty big, print it modulo 10 9 +7 . Input The first line contains 1 ≤ T ≤ 10 5 , number of test-cases. Each of following T lines contains 1 ≤ N ≤ 10 7 , number of types/places. Output For each test case, print the number of possibilities for given number of types/places modulo 1000000007. Example Input 5 2 3 10 100 666 Example Output 1 2 1334961 944828409 769756093
34,216
Ada and GCD (ADAGCD) Ada the Ladybug got interesting homework. She had to count gcd of a few numbers. As she is a great mathematician, she done it in meanwhile (in fact, she submited it during the class it was assigned in). The teacher was impressed so he gave Ada a bonus homework (for bonus points). It is same as previous one with a little difference - there are bigger numbers. Since the number are too large to be written as numbers, they are written as product of lesser numbers. Find their gcd. Input The first line of input consists of 2 ≤ N ≤ 10 6 , the number of numbers for which Ada wants to find their gcd. Each of the next N lines contains an integer 1 ≤ M i < 10 6 followed by M i integers, 1 ≤ A j ≤ 10 7 , the numbers whose product is the i th number. The sum of all M i won't exceed 10 6 Output Print the gcd on a single line. Since this number might be pretty big, output it modulo 10 9 +7 ( 1000000007 ) Example Input 1 3 4 1 2 3 4 1 36 2 6 5 Example Output 1 6 Example Input 2 2 11 1 2 3 4 5 6 7 8 9 10 11 2 1024 15 Example Output 2 3840
34,217
Ada and Numbering (ADANUM) Ada the Ladybug has sequence of different vegetables (for simplicity represented by numbers). She has a few interesting questions of following form: Choose some continuous subsequence of vegetables, then assign each kind of vegetable a distinct positive number. She wants to assign them in a way that the sum (of assigned numbers) over all vegetables will be as low as possible. Input The first line contains two integers 1 ≤ N, Q ≤ 2×10 5 , the number of vegetables and number of questions. Next line contains N integers 1 ≤ A i ≤ 10 9 , the kinds of vegetables. Next Q lines contains two integers 1 ≤ I ≤ J ≤ N , the left and right indices of Ada's questions. Output For each question answer the minimal possible sum. Example Input 1 10 5 1 1 3 2 4 1 3 1 1 4 1 3 1 10 5 10 3 5 5 8 Example Output 1 4 19 10 6 7 Example IO explanation Assign 1 to 1 and 2 to 3 Assign 1 to 1, 2 to 4, 3 to 3 and 4 to 2 (swapping 4 and 3 would work too) Assign 1 to 1 and 2 to 4 and 3 to 3 Assign 1 to 4, 2 to 3 and 3 to 4 (but any permutation would do) Assign 1 to 1 and 2 to 4 and 3 to 3
34,218
Ada and Carrot (ADACAROT) Ada the Ladybug is a great farmer. She has many places where she grows vegetables. She wants to grow two completely different kinds of vegetable: carrots and baby carrots . She wants to connect them by paths in such way, that she can get from any carrot (or baby carrot) to any other carrot (or baby carrot). She isn't amused by building itself, so she wants to make least number of paths, which is sufficient to make all carrots (and all baby carrots) connected. Due to regulations of Earwigean Union ( EU ), a carrot can't be connected to other carrot (and same is true for baby carrots) [so basically, she can connect only "baby carrots" to "carrots"]. Ada also wants to keep track of everything, so she will somehow distinguish between each carrot and between each baby carrot (and also between each place). She is wondering in how many ways she can plant carrots (and baby carrots) and connect them by ways, so that it corresponds to EU regulations. Input The input contains up to 200 lines. Each line consists of single integer 2 ≤ N ≤ 2*10 5 , the number of places to which carrots/baby carrots shall be placed (note that she won't waste so she will fill all the places). Output For each line of input, print the number of ways, to plant carrots and baby carrots in such way, that it coresponds to EU regulations. Since this number might be pretty big, output it modulo 10 9 +7 ( 1000000007 ) Example Input 2 3 4 10 66666 Example Output 2 12 144 452744977 57191401
34,219
Ada and Species (ADACABAA) As you might know, Ada the Ladybug is a farmer. She needs to choose some species of vegetables. Each vegetable disposes with four important attributes. We say that a vegetable is worse than another vegetable, if all of its four attributes are greater. She wants to eliminate the list of vegetables, so only vegetables, which are not worse than any other vegetables remains. Input The first line contains integer 1 ≤ N ≤ 2*10 5 Each of the next N lines contains four integers 1 ≤ X, Y, Z, W ≤ N . It is guaranteed, that all X attributes are distinct for all vegetables. The same is true for Y, Z and W (so in fact, there are four permutations of numbers from 1 to N ). Output Print the number of vegetables, which are not worse than any other vegetable. Example Input 1 3 1 1 1 1 2 2 2 2 3 3 3 3 Example Output 1 1 Example Input 2 10 8 9 9 2 3 7 2 4 5 5 10 10 9 3 5 9 4 6 8 6 2 8 1 7 1 2 6 1 7 4 7 5 6 1 3 8 10 10 4 3 Example Output 2 5
34,220
Ada and Travelling Salesman (ADASALES) Ada the Ladybug lives in Bugladesh. It is a very specific country - there are plenty of cities, but since the government doesn't "waste" money, there is only one simple path between each pair of cities. Ada is working as Traveling Salesman. She travels between cities, buying and selling products. A product has fixed price in each city (same for buy/sale). Since Ada travels with bike (to avoid payments for travels) so she can carry at most one item at a moment. She is currently in some city, and she wants to choose such city, that she will make as much money as possible by travelling to that city (by simple path). Can you help her? Input The first line will contain 0 < N ≤ 10 5 , 0 < Q ≤ 5×10 5 , number of cities and number of queries respectively. Then one line with N integers follow, 1 ≤ A i ≤ 10 9 , the price in i th city. Afterward N-1 lines follow, each containing two numbers 0 ≤ i, j < N ( i ≠ j ), meaning that there is a simple path between city i and city j . Then Q lines follows, each containing exactly one integer 0 ≤ i < N - the city in which Ada begins. Output Print Q lines, the maximal amount of money, Ada can earn. Example Input 6 6 1 2 3 4 5 4 1 0 1 2 1 3 3 4 4 5 0 1 2 3 4 5 Example Output 4 3 3 1 1 2 Example Input 5 2 1 5 2 4 3 0 1 1 2 2 3 3 4 0 2 Example Output 6 3 Output explanations [Possible destination cities of first example input] 4 4 4 2 2 2 Note that some of the destinations might have ended somewhere else, but it would result in same income!
34,221
Ada and Cucumber (ADAPICK) Ada the Ladybug works as farmer. It's the season of cucumbers and she wants to harvest them. There lie many cucumbers all around her house. She wants to choose a direction and follow it until all cucumbers in that direction are collected. Lets consider Ada's house as centerpiece of whole universe, lying on [0, 0] . The cucumbers are defined as lines on plane. No cucumber goes through Ada's house (and no cucumber touches it). How many cucumbers can Ada pick in one go if she chooses the best direction possible? Input The first line contains an integer T , the number of test-cases. Each test-case begins with an integer 1 ≤ N ≤ 10 5 Afterward N lines follow, with four integers -10 6 ≤ x 1 , y 1 , x 2 , y 2 ≤ 10 6 , the beginning and end of each cucumber. Each cucumber has positive length. Sum of all N over all test-cases won't exceed 10 6 Even though cucumber will not go through house, they might touch, intersect or overlap other cucumbers! Output For each test-case print one integer - the maximal number of cucumbers which could be picked if Ada chooses a direction and picks every cucumber lying in it. Example Input 5 4 2 1 -1 4 -2 1 1 3 -3 2 0 5 -2 -2 5 1 3 -2 2 -2 -2 2 2 2 -2 -3 -3 -6 -3 3 -2 1 -3 4 3 1 5 5 -2 -2 2 -2 6 -1 5 -6 5 -3 -3 5 -3 -2 -5 5 -5 -1 -6 5 -6 5 1 5 5 6 6 6 -11 3 1 3 4 3 4 2 4 -1 5 1 6 6 Example Output 3 2 1 4 2 Possibly harvested cucumbers 1 2 3 1 3 1 2 3 4 6 2 3
34,222
Ada and Apple (ADAAPPLE) Ada the Ladybug is currently on a trip on apple tree . There are many apples on the tree connected with branches. Each apple is inhabited by either Psylloideas or by Woolly Apple Aphids. Psylloideas and Aphids doesn't like each other, so it is strictly prohibited to walk from apple of Psylloideas to apple of aphids (and vice versa). Ada has some questions, whether it is possible to go from node I to node J . Anyway note, that as Aphids and Psyllodeas doesn't like each other, they sometime conquer an apple of the others. Also note, that it is a real apple tree (not some bush) so no apple is connected with more than 50 other apples. Input The first line contains 1 ≤ N, Q ≤ 3*10 5 , number apples on tree and number for queries. The next line contains N characters (either 0 or 1), indicating whether i th apple belongs to Psyllodeas or to Aphids. Next N-1 lines contains two numbers, the branches (edges) of apple tree ( 0 ≤ I, J < N , I ≠ J ). Each of following Q lines contains one of following types of queries: 0 I , 0 ≤ I < N , meaning that ownership of I th apple has changed. 1 I J , 0 ≤ I, J < N , question, whether it is possible to go from I th to J th apple. Output For each query of second kind (1) print "YES", if it is possible or "NO" if it is impossible! Example Input 8 11 00111100 0 1 1 7 1 2 2 3 2 6 2 4 4 5 1 1 2 1 0 7 1 6 5 1 2 3 1 6 7 0 2 1 1 2 1 0 7 1 6 5 1 2 3 1 6 7 Example Output NO YES NO YES NO YES YES NO NO YES
34,223
Ada and Aphids (ADAAPHID) Ada the Ladybug breeds aphids. Whenever a new aphid is born, she assigns him an ID. She did that for long time but as she can't remember the ID's she sometime made duplicates. She wanted to avoid such situation so she extended the ID to pair. She has also chosen a random number, which she assigned to aphid and then she made second integer of ID as sum of values of all aphids with ID lesser or equal to current ID (including current ID). She wants to know the ID of each aphid. Please, read the input section carefully. Input The first line contains 1 ≤ Q ≤ 3*10 5 , number of aphids added. Let L be the second integer of last aphid's ID (beginning with 0). The next Q lines contains two numbers A, V , 0 ≤ A, V < 2 60 , where A ⊕ L is the first integer of aphid's ID and V ⊕ L is the random number ( ⊕ stands for XOR). 1 ≤ A ⊕ L < 2 60 1 ≤ V ⊕ L < 1000 Output For each query print both number's of aphid's ID. Example Input 7 1 1 3 3 4 0 3 2 5 6 13 13 19 19 Example Output 1 1 2 3 7 6 5 7 2 4 9 20 7 18 Input after XOR 7 1 1 2 2 7 3 5 4 2 1 9 9 7 7
34,224
Bernoulli numbers (BERNULLI) Your task is to compute natural logarithm of the absolute value of the  Bernoulli number  for many integer parameters  N . I/O format is the same as in  BINARYIO . Input Array of unsigned 32 bit integers in binary format (use fread  in C/C++) To read unsigned N use fread(&N, sizeof(N), 1, stdin)   instead of usual scanf("%u", &N) until the end of file. For each test case 2 ≤  N  < 2 32 , N is even. There will be up to 1,250,000 numbers in input file. Output Array of  doubles  in binary format (use fwrite  in C/C++) To write double a use fwrite(&a, sizeof(a), 1, stdout)   instead of usual printf("%lf\n", a) . For each N  output ln(|B N |) with absolute or relative error less than 10 -15 Example Input: 4 10 50 Output: -3,4011973816621553754132366916069 -2,580216829592325170273661603119 57,277060811865704087099873424857 Sample input and output are readable for your convenience!!! TL = 5 * My time
34,225
THE LAST SHOT (LASTSHOT) Tony Stark is on the mission to save the world from Loki's army so he spread N bombs in the enemy region. He spread the bombs in such a way that a bomb can be in range of another bomb i.e. say bomb B1 is in range of bomb B2 , when bomb B2 explodes it will trigger bomb B1 and it also get explode but vice-versa might not be true because the bombs are of different of range. As he is running out of energy so he left with one shot to trigger the bomb .Now he ask Jarvis to find most appropriate bomb which he can trigger to make maximum impact. Impact is basically number of bombs get explode. Can you help Jarvis to do so? Input First line contains two integer N and M denoting number of bombs and number of relation between the bombs. 1 ≤ n ≤ 10000 1 ≤ m ≤ 10000 Next M lines contain two integer A and B denoting bomb B is in range of bomb A. 1 ≤ A ≤ N 1 ≤ B ≤ N Output A single line containing MAXIMUM IMPACT. Example 1 Input: 4 3 1 2 2 4 1 3 Output: 4 Example 2 Input: 4 3 1 2 2 1 2 3 Output: 3
34,226
Class Leader (CLSLDR) This is new year in Planet X and there is something special! A classroom in this planet is looking for a new class leader using an unique game! These are the ways how the game is played. There are n students in the class. Each student is labeled from 1 (first student) to n (last student). A paper is given to m -th student. The next o -th student who gets the paper quits the game. The paper is passed until there is one last student who hasn't quitted the game. The student becomes the class leader. Now, your task is to find the number of such student. Input The first line contains a number T (0 <= T <= 10 6 ). Each of the next T lines contains 3 integers which are n (0 < n <= 10 3 ), m , o (0 < m, o <= n) and are separated by a single space. Output For each test cases, print the required answer. Example Input: 2 4 1 2 5 2 3 Output: 2 1 Explanation for Test Case 1 1 2 3 4 → The paper is being held by student 1. Pass the paper by 2 students. Now, the paper is being held by student 3. 1 2 4 → Student 3 quits. Pass the paper by 2 students. Now, the paper is being held by student 1. 2 4 → Student 1 quits. Pass the paper by 2 students. Now, the paper is being held by student 4. 2 → Student 4 quits. Student 2 becomes the class leader.
34,227
Sabbir and Game (SABBIRGAME) Sabbir is a little boy. he loves to play. One day his friend Taskin suggested a new interesting game. There are n levels in the game. One should pass all the levels with a positive life-point. In some level one can increase his life-point by defeating the villain of the game or lose some life-point when one can't defeat the villain. Sabbir knows the points he is going to lose or increase in each level. Determine the minimum life-point Sabbir should have initially (at the starting of the game) to pass all the levels with a positive life point. Input Input consists of at most 100 test cases. First line consists of a single integer T (1 <= T <= 100) number of test cases. Each test case is consists of two lines. first line consists of an integer n (1 <= n <= 1000) Second line consists of n space separated integer a 1 , a 2 ... a n-1 , a n (-10 7 <= a i <= 10 7 ) Output for each test case print an integer in one line , the minimum life-point Sabbir will need initially. Example Input: 3 3 5 -8 3 4 1 2 -3 5 3 1 0 3 Output: 4 1 0 Explanation First case, if Sabbir have 4 life-points at first. Sabbir will have 9 points after playing 1st level, he will have 1 point after playing 2nd level, he will have 4 points after playing 3rd level... his points never becomes less than 1 (remains positive). If he starts with a lower point (less than 4) initially, he will die at the 2nd level and can't pass all the levels. So, 4 is the minimum answer.
34,228
Ada and Unique Vegetable (ADAUNIQ) Ada the Ladybug is cultivating vegetables. She has a long furrow full of different kinds of it and she wants to know the number of unique vegetables on a segment of the furrow. As the cultivation is a dynamic process, a kind (on a single position) might become another kind during this process. Given furrow and a few updates, can you answer questions asking about number of unique kinds of vegetable on a segment? Input The first line contains 1 ≤ N, Q ≤ 2×10 5 , length of furrow and number of queries. Next line contains N integers 0 ≤ A i ≤ 2×10 5 , the kind of i th vegetable Each of following Q lines contains one of the following kinds of query: 1 I V : The vegetable on index 0 ≤ I < N , will be changed to kind 0 ≤ A ≤ 2×10 5 2 L R : 0 ≤ L ≤ R < N , the index of left/right bound of segment for which you want to know the number of unique kinds. Output For each query of second kind, print the number of unique kinds of vegetable. Example Input 8 8 1 2 3 3 1 2 3 3 2 1 3 2 0 3 2 0 7 1 3 4 1 7 0 2 1 3 2 0 3 2 0 7 Example Output 1 2 0 3 4 2
34,229
Sabbir and gcd problem (GCDS) Sabbir is a little boy. He loves math very much. One day his friend Taskin gave him a very hard task. Taskin gave him n numbers a 1 , a 2 , a 3 , ... a n Taskin asked for a minimum integer number x ( x > 1 ) such that gcd(x, a 1 ) = 1, gcd(x, a 2 ) = 1, ... gcd(x, a n ) = 1 . In other words you have to find a minimum integer x (x > 1 ) such that ∀i, i ∈ [1...n], gcd(x, a i ) = 1 Note: gcd is greatest common divisor. Input In the first line there will be an integer T , denoting the number of test cases. Each test case is consists of 2 lines. In the first line there will be n , denoting the number of integers and next line contains n space separated integers a 1 , a 2 , a 3 , ... a n . Constraints 1 <= T <= 10 1 <= n <= 10 5 1 <= a i <= 10 7 Output for every case print one integer x in one line. Note: x should be greater than 1. Example Input: 3 3 5 7 25 4 1 2 3 4 1 2 Output: 2 5 3
34,230
Ada and Plum (ADAVISIT) Ada the Ladybug is visiting her friends who live on a plum tree . As many bugs like her, she has a friend in each node. She has already planned in which order she will visit them. She does that in following manner. If she is standing at a node i in the morning, she will choose shortest path to friend with number i+1 . Afterward, she stays there until next morning. First day she "magically" appears on node number 1 and as she arrives at node N , she ends her journey. Your task is to find (for each node), the number of days she visited it (this means she either begins in it, ends in it or passes through it). Input The first line contains 1 ≤ N ≤ 4×10 5 , number of nodes on tree. Each of next N-1 lines contains two integers 1 ≤ I, J ≤ N , I ≠ J , the nodes which are connected by an edge. Output Print N lines with and integer indicating number of times i th node was visited. Example Input 5 1 2 2 5 2 4 5 3 Example Output 1 4 2 2 3 Example Input 2 10 1 3 1 5 5 2 5 9 9 7 9 10 6 2 4 2 8 4 Example Output 2 3 8 2 4 8 2 2 2 4 1
34,231
Jerry and his cheese (JERRY) Have you heard about Jerry from Tom & Jerry cartoon, we all loved that when we were young. Jerry has been put into a grid of n by n cells, with only k cells containing cheese. The rest of the cells are empty. Now, Jerry can start his journey from any cell of the grid he wants and move from one cell to any of its four adjacent cells. That is he can move up, down, left, or right in one move. When he reaches a cell containing cheese he can eat that cheese. Otherwise, he will move to the next cell. If the initial cell that Jerry lands on has cheese in it, he can eat that too. Unfortunately for Jerry, he can’t plan his trip very well. He can only rely on his sense of smell. From any cell, he will choose the path to go to the closest cell with cheese. Here, we calculate the distance between any two cells using the definition of “Manhattan Distance”. If there are multiple cells with cheese with the same distance, he chooses top most cell among the tied the cells. If even after this the tie is not broken (i.e. the tied cells are in the same row) then he chooses the leftmost cell. Also, Jerry can not eat all k cheeses as he gets full after eating c cheeses. It is guaranteed that there are at least c cheese in the grid. After eating c cheeses his journey ends immediately and is taken out of the grid. As Jerry does not like to run around more than he has to, he wants to minimize the number of cells he needs to visit. Now, as a friend of Jerry, your task is to figure out, which cell Jerry should start his journey, so that he has to move to least number of cells to eat c cheeses. You don’t need to tell us about the starting cell though, only tell us the minimum moves required by Jerry to eat c cheeses. Note that, the “Manhattan Distance” between two points in a grid is based on a strictly horizontal and/or vertical path (that is, along the grid lines), as opposed to the diagonal or “as the crow flies” distance. The Manhattan distance is the simple sum of the horizontal and vertical components, whereas the diagonal distance might be computed by applying the Pythagorean theorem. Input The first line contains an integer, T , denoting the number of test cases to follow. For each test case, the first line contains 3 space separated integers: n , k , and c . Next n lines represents the grid. Each of those n lines has n characters representing each cell. Each cell can is represented either by ‘.’ representing empty cell and ‘*’ representing cell with cheese. Constraints T ≤ 100 1 ≤ n ≤ 100 1 ≤ k ≤ 1000 k ≤ n 2 1 ≤ c ≤ 10 c ≤ k Output For each test case print the least number of moves Jerry has to make to eat c cheeses. Example Input: 3 3 2 1 ..* *.. ... 3 3 2 *.* .*. ... 6 6 4 *.*.*. .*.... ...... ....*. *..... ...... Output: 0 2 6 Explanation For the first test case, we can drop Jerry to any of the two cells containing cheese so that he can immediately eat 1 cheese and does not have to move at all. For the second test case, again we can drop Jerry on any of the cell with cheese. For example, Jerry can be dropped on the second cell of the second row from the top. Jerry eats cheese on this cell. There are two remaining cells with cheese, both of which are 2 moves away. However, Jerry will choose the the first cell on the first row to move next. For the last test case, Jerry can be dropped on the second cell on the second row. From there, Jerry moves to the first cell on the first row and continue moving right until he eats 4 cheeses in total.
34,232
Non Coprime Sequences (COPSEQ) You are given two integers, n and m . Find and print the number of sequences of length n which satisfy:  All elements of the sequence are positive divisors of m  For any two adjacent elements, say p and q, there exists at least one prime which divides both of them. Print the number of such sequences modulo 10 9 +7 Input The only line of input contains two integers, n and m. Constraints 0 < n ≤ 10 5 0 < m ≤ 10 18 Output Print the number of valid sequences modulo 10 9 +7 Example Input: 2 10 Output: 7 Print the number of such sequences modulo 10^9 + 7
34,233
Sabbir and gifts (SGIFT) Sabbir is a little boy. he went to a gift shop with his mother. There were n different types of gifts in the shop. All the gifts were attractive to Sabbir. He wanted to buy all the gifts which are in price range a <= p <= b. You are given prices of all the gifts and a , b . Sabbir's mother need your help. Please calculate the total amount of price of all gifts of that range for Sabbir's mother. Input In the first line there will be n , the number of gifts in the shop. In the next line there will be n integers p 1 , p 2 , p 3 ... p n denoting price of every gift. In the third line there will be Q , the number of queries. The next Q lines contain two integers a and b . Constraints 1 <= n <= 10 5 . 1 <= p i <= 10 9 . 1 <= Q <= 10 5 . 1 <= a, b <= 10 9 . Output Print Q lines. Every line contains one integer, sum of all prices for that range given in the query. Example Input: 7 1 3 2 1 5 2 2 4 1 2 1 5 3 5 4 5 Output: 8 16 8 5 NOTE: for first query, Sabbir will buy all the gifts of prices 1, 2, 1, 2, 2. So, sum is 8. For second query, Sabbir will buy all the gifts, so the sum is 16.
34,234
Non Coprime Sequences(Hard) (COPSEQH) Define F(n, m) to be the number of sequences of length n which satisfy: All elements of the sequence are positive divisors of m For any two adjacent elements, say p and q, there exists at least one prime which divides both of them. You are given two integers, n and m. Find the values of F(1, m), F(2, m), ... F(n, m) modulo 10 9 +7 Input The only line of input contains two integers, n and m. Constraints 0 < n ≤ 10 5 0 < m ≤ 10 18 Output Print the values of F(1, m), F(2, m) ... F(n, m) modulo 10 9 +7 in a single line separated by space. Example Input: 2 10 Output: 4 7
34,235
Ada and Tomato (ADATOMAT) Ada the Ladybug grows tomatoes. She has a very long furrow full of them. At the day of harvest, she picks all tomatoes, sorts them by size, index them (from 1) and sell them for price of " size × index ". How much money will she make, if she sells all of them? As the nature is very beautiful (and Ada is great mathematician), she found the pattern for sizes of tomatoes. The pattern works in (hopefully well known) way: Let us have tomato of size X i , then X i+1 will be counted as X i+1 =X i *a+b mod M . M (modulo) is equal to 10 9 +7 (1000000007). Input The first line contains 1 ≤ T ≤ 200 , the number of test-cases. Each test-case contains four numbers N, a, b, X 1 : 1 ≤ N ≤ 2*10 7 , the number of tomatoes. 0 ≤ a, b, X 1 < 10 9 +7 - described above (X 1 is the size of first tomato). Sum of N over all test-cases will not exceed 5*10 7 . Output For each test-case output the sum of all prices modulo 10 9 +7 . Example Input 5 2 2 3 1 3 1 1 1 5 1 2 1 4 1 0 1 20 5 6 7 Example Output 11 14 95 10 150690584 Sizes of tomatoes for each input 1 5 1 2 3 1 3 5 7 9 1 1 1 1 7 41 211 1061 5311 26561 132811 664061 3320311 16601561 75195297 83007811 375976491 399412248 415039061 632654193 879882454 926530843 985306173 997061239
34,236
Ada and Mulberry (ADABERRY) Ada the Ladybug grows a mulberry tree (which is rooted at node 0). At the beginning, it has a mulberry fruit of distinct size growing on every node. As the time flows, new mulberry fruits appear on each node (additionally - meaning the previous mulberry fruit still remains on given node) - while keeping the condition of distinct sizes. Ada observes every single fruit and for each new fruit she is asking you to tell her the number of lesser fruits in the subtree of given node. Input The first line contains two integers 1 ≤ N, Q ≤ 2×10 5 , size of mulberry tree. The next line contains N integers: 0 ≤ A i ≤ 10 6 , the size of mulberry fruit in each node. Each of the next N-1 lines contains two integers 0 ≤ a, b < N , meaning the branch (edge) between given nodes. Each of the next Q lines contains two integers a S : 0 ≤ a < N (the node in which new fruit grows) and 0 ≤ S ≤ 10 6 (size of the fruit) Output For each query, print the number of lesser mulberry fruits which grow in subtree of node where new mulberry fruit grew. Example Input 7 8 10 9 13 17 11 20 18 0 4 0 1 1 2 1 3 2 5 2 6 0 21 0 8 2 15 3 22 1 14 2 19 0 12 1 16 Example Output 7 0 1 1 2 3 4 4
34,237
Namit In Trouble (NGIRL) Namit's girlfriend's birthday is coming next week. He went to a gift shop and saw N gifts are arranged in a single row in such a way that the position at which the gift is placed is equal to its price. (Position starts from 1.) Namit's girlfriend being a maths student like those numbers which have exactly 3 divisors, so Namit decide to buy only those gifts which are placed at a position which have only 3 divisors, but Namit's girlfriend likes gifts whose price are above a certain amount K . Now Namit wants to know total choices he have and how many gifts his girlfriend like for a given value of N. Input Input starts with 1 ≤ T ≤ 1000 (number of test cases). Then T lines follows each containing two integer 1 ≤ N < 10 10 (number of gifts at gift shop) and 1 ≤ K ≤ 10 10 . Output You program should output two values indicating total number of choices and the number of gifts Namit's girlfriend likes. Example Input: 3 10 2 20 7 10 4 Output: 2 2 2 1 2 1
34,238
PLAYGAME (PLAYGAME) Hemlata and Ritu were playing a game from a number of coins. Hemlata was jealous of Ritu. She wanted to win at all cost. A stack consists of n coins. Any player can take either 1, 2 or 5 (any one number of coins) coins from stack at a time. Both Hemlata and Ritu play their moves alternatively. Hemlata always starts first. Both play optimally. Your job is to predict the output beforehand. A player who can't take any coin loses the game. A player can take only one of 1, 2, 5 number of coins at a time in a move. Input First line contains number of test cases t . 0 < t ≤ 10 5 . An integer n denoting number of coins. 0 ≤ n ≤ 10 18 . Output For each test case print "Hemlata" if Hemlata wins, else print "Ritu" if Ritu wins (without quotes) in different lines . Example Input: 3 1 2 3 Output: Hemlata Hemlata Ritu
34,239
Ada and CAPTCHA (ADAROBOT) Ada the Ladybug just got an innovative idea (which might be a rival of captcha): She made following function - F(a) = least significant 1-bit of a (indexed from 1). She also made following recursive function T(N) = F(N×(N-1)) 3 + T(N-2) , where T(0) = 0, T(1) = 0 . Her idea is following- Instead of asking for captcha, she uses an opposite method: She gives you even N and you have to answer T(N) - if your answer is correct, then you are definitely a robot and you won't be let in. As her good friend she asked you to program a checker for her. Input The input begins with an integer 1 ≤ Q ≤ 10 6 , number of queries. The next Q lines contains an even integer: 2 ≤ N ≤ 2×10 8 Output For each query, print T(N) Example Input 5 8 4 2 20 1000 Example Output 107 35 8 310 23988 Little explanation F(2)=2 F(12)=3 F(30)=2 F(56)=4 F(90)=2 F(132)=3 F(182)=2 F(240)=5 F(306)=2 F(380)=3
34,240
Zen And His Crush (ZCR) Zen has a Crush and is always fantasizing about her. He is so restless now, that he has decided to meet her and express his immense feelings about her. He fears a lot of being rejected that's why he wants to examine his luck. Zen has  N  biased coins where the probability of getting Head from  i th coin is P i . His luck of being accepted is the probability of getting  exactly K  heads when N coins are tossed simultaneously. Zen is weak in programming and asking for help. Can you help him to calculate his luck? Input First Line of the input file contains,  T -number of test cases. ( 1 <= T <= 100 ). Each test case followed by two integers,  N  and  K . ( 1 <= N <= 1000, 0 <= K <= N ) Next line contains  N -space separated real values,  P i . Output For each test case, you have to print desired output (with up to  10  decimal places.) Example Input: 1 3 2 0.0 0.5 1.0 Output: 0.5000000000
34,241
TV Schedule (URJC2_A) The schedules of a TV Channel are very important nowadays, it reflects the shows they’re hosting and this can contribute to gather more or less people, hence, making more or great money to them! You have been called to make a program that, given the current program of the TV shows on the channel, answer the queries of the audience. To answer the query of the audience you must show the next program that follows the one they are currently watching, you may assume that the TV programs are cyclic and the final show ends at 23:59, after that, the first show will begin at 00:00    Input The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases. The first line will be a number N denoting the number of tv shows, then, N lines will follow, each line will contain a start hour in the format HH:MM and the end hour with the same format, then, the name of the program that may contain lowercase, uppercase letters and will not exceed 100 characters. You can assume that every show will cover the whole day (all 1440 minutes of the day) and that the end date is exclusive (meaning that two consecutive programs will share their end date and start date respectively), it is not guaranteed that a program name will be unique along the day. After that, you will receive an integer Q denoting the queries that will make the audience, then, Q lines, for each query you will receive an hour with the format HH:MM. Output For each case you must print Q lines, each line will contain a string denoting the program that follows the one currently being watched. Note that we consider that the program starts exactly at the given hour. Sample Input Sample Output 2 3 00:00 12:00 Noticias 12:00 14:00 AquiNoHayQuienViva 14:00 00:00 Informeciales 2 00:51 23:10 5 20:00 23:50 DocumentalDe 00:00 00:06 NoticiasUrgentes 14:00 20:00 LaQueSeAvecina 00:06 14:00 YLoSabes 23:50 00:00 JulioIglesias 3 19:50 23:49 00:00 AquiNoHayQuienViva Noticias DocumentalDe JulioIglesias YLoSabes Constraints • 1 ≤ N ≤ 1440 • 00 ≤ HH ≤ 23 • 00 ≤ MM ≤ 59 • 1 ≤ Q ≤ 100 • 1 ≤ |name of program|≤ 100
34,242
Playing Darts (URJC2_B) Lucy and her friends are heading to the bar to play darts, the forever fierce battle between drunk people to show who’s the best at throwing some sharpened darts into a board. Seems like a lot of fun. As crazy as it may appear, Lucy and her friends have mad skills when playing darts, as they may all win flawlessly (and this is not fun at all), they have decided to challenge themselves a little bit with some luck. They will draw from a bowl N numbers ranging from 1 to 60 and then they will try to reach 0 at a standard game of 301. When playing 301, you start your score at 301 points, for each turn you have three throws, for each throw you will substract the value thrown to the current value you have, if, for some reason you exceed the score you must get to be at 0 points, nothing you’ve done at that turn will be taken into count. If you get to 0 at some point of the game, you win. After your turns ends, the other player’s start its throws For instance, if you have 32 points left on your board to get to 0 and you throw 2 darts at 16, you win, but if you throw a dart at 17 and 16 (thus earning 33 points), you reset yourself to 32 again and your turn is immediately over, and if you score something like 8, 8 and 12 (earning 28 points), next turn you will have to make 4 points to win. Lucy and her friends want to know who’s going to be the expected winner at the darts game, because if that person does not win, he or she will pay all the beers! Input The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases. For each test case you will have an integer N and K representing, respectively, the number of players and the number of scores they will have to make on the board. Then, N lines will follow with K integers separated by a single space denoting the score Kj that a player Ni must make on that turn. For simplicity, we will assume that they can score any number between 1 and 60 (inclusive) regardless of the board points configuration and that after they throw K darts, they will stop throwing and, if no player has won yet, declare a tie. Output For each case you must print the number (1-index based) of the player that is expected to win the standard game of 301 respecting the order of the input, if there is no player that wins the game after throwing all of its darts, print ”TIE” (without quotes) Example Input: 3 3 4 60 60 60 58 60 60 60 60 60 59 58 57 3 9 60 60 60 60 40 10 10 1 60 10 20 30 40 50 60 60 60 60 60 60 60 60 60 1 60 60 60 3 9 60 60 60 60 50 10 5 1 50 60 60 60 60 40 10 5 1 5 60 60 60 60 60 60 60 60 60 Output: TIE 3 2 Constraints • 1 ≤ N ≤ 100 • 1 ≤ K ≤ 301 • 1 ≤ Ki ≤ 60 Explanation of the third case: at the end of the first round, player 1, 2 and 3 scored 180 points, at the second round, player 1 scored 120 (1 points left), player 2 scored 110 (11 point left) and player 3 scored 180 points (131 left as it got busted), by the next round, player 1 bust out with one throw at 5 points and then, player 2 wins by scoring in three throws 5,1,5 (earning 11 points).
34,243
Stressful Activities (URJC2_E) The finals are coming and we, as sensitive people, cannot handle that much of stress. Each year some students will fail their tests because of nervousness or stressful situations in their normal lives, this is why the professors at a certain university have called you. Each of the K students will tell you what they’re managing to do in some period of N days, some activities can be stressful (will be denoted by a positive integer) and some may be relaxing (denoted as a negative integer), the professors then will ask you if they put the final exams in a range of D days, how many students will be full of stress and how many students will not based on a threshold. This is, if the sum of the range of days is less or equal than a set threshold for each student. Input The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases. The first line of each test case will contain three numbers; K students, a threshold H of stress and the number N of days studied, after that, K lines will follow with N numbers separated by a space denoting the stress that the student Ki is expected to receive on the day Nj . After that, a number Q will follow and on the next Q lines there will be two integers Ds and De denoting the days where the finals are to be applied (inclusively). Output For each test case you must print Q lines with two integers, the number of stressed students (if the stress exceeded the threshold) and the number of not stressed students separated by a dash and spaces for each period of days asked. Example Input: 1 5 10 5 5 1 2 5 -3 -1 -2 -3 -4 -5 1 6 91 1 2 1 0 9 7 2 1 1 2 3 2 4 1 5 1 3 3 5 3 3 Output: 2 - 3 1 - 4 2 - 3 1 - 4 Constraints • 1 ≤ K ≤ 100 • 1 ≤ N ≤ 50,000 • 1 ≤ H ≤ 100,000 • -1,000 ≤ Ni ≤ 1,000 • 1 ≤ Q ≤ 20,000 • 1 ≤ Ds ≤ De ≤ N
34,244
Fractals (URJC2_F) What is a fractal? According to wikipedia: A fractal is a mathematical set that exhibits a repeating pattern displayed at every scale. We are interested in developing a solution and create some fractals! This time we are interested on creating the ”H” fractal. The process to create it is as follows: At scale 1, you have the ”H-H” string. At scale 2, you will copy the strings into four corners, each copy separated by a single space (row and column-wise). You must connect the vertical copies with the pipe character or ’|’ and the horizontal copies with a dash character ’-’ between the pipes that connect the vertical copies (see the samples as clarification). At scale 3 and further, you will repeat the step done on scale 2. Thus generating the fractal. Input You will receive a single integer N denoting the scale of the H fractal we want to generate. Output You must output the generated H fractal as described above, in addition, the generated fractal MUST NOT have trailing spaces, this means that, after the last non-whitespace character of each row is printed, there must be nothing else but a newline written as output. Example Input 1: 1 Output 1: H-H Input 2: 2 Output 2: H-H H-H |---| H-H H-H Input 3: 3 Output 3: H-H H-H H-H H-H |---| |---| H-H|H-H H-H|H-H |-------| H-H|H-H H-H|H-H |---| |---| H-H H-H H-H H-H Constraints 1 ≤ N ≤ 10
34,245
Eat Pray Love (AGPC01G) One of your friends was in relationship with multiple people at once and it didn’t end very well. Thus he/she chose the path of righteousness and decided to stay in only one relationship or stay single. But not only that, he/she became a motivational speaker and formed an organization to help people to walk through this path. N people joined his/her organization. He/She takes one person and he/she either pairs that person up with another person in a relationship or keeps that person single. Let’s assume that every person can be paired up with every other person. In how many ways he/she can do that? Input First line of input will be T (1 ≤ T ≤ 100000), denoting the number of test cases. Next T lines will contain one integer N (1 ≤ N ≤ 100000) per line. Output For each test case print correct answer describe in the description. As output can be large, print it modulo 1000000007. Example Input: 2 3 100000 Output: 4 823421181 Explanation For case one, let’s assume they are numbered 1 2 and 3. Formation can be: {1} {2} {3} - every person is single. {1} {2, 3} - one is single and two are in a relationship. {1, 2} {3} - one is single and two are in a relationship {1, 3} {2} - one is single and two are in a relationship. Thus the answer is 4.
34,246
Ada and Zoo (ADAZOO) Ada the Ladybug is a well know farmer. As she has experience with building fences and breeding animals, she was asked by leader of local zoo - Lichsteiner Leech - to help them design a paddock for animals. The problem is following: The zoo breeds very rare beasts called Tyg3Rs. There are few of them in a N x N square paddock with squares have different heights. The Tyg3Rs live in (little) squares and the breeders want them to play with each other. At first it is not possible to travel between distinct squares, but it is possible to connect any two adjacent squares for cost of absolute difference of their heights (by making slope). Now, for each subset of Tyg3Rs, the zoo wants to know minimal price to connect the squares in such way, that each Tyg3R can get to each other. As the output would be pretty big, they just want you to sum these costs. As her good friend (and as the instances are too big for her to handle), she has asked you to help her with this problem. Input The first line contains T , the number of test-cases. The first line of each test-case contains 2 ≤ N ≤ 17 , the size of big square. Each of the next N lines contain N integers, the heights of each square. Each number is between 0 and 1000 . The next line contains 1 ≤ Q ≤ 10 , the number of Tyg3Rs. The next Q lines contains two integers: 0 ≤ x, y < N , the coordinates of Tyg3Rs. Note that multiple Tyg3Rs might already live in the same square. Output For each test-case print the sum of costs of cheapest way to connect all subset of Tyg3Rs. Example Input 4 3 1 2 1 2 1 2 1 2 1 3 0 0 0 2 2 1 3 5 5 5 7 5 5 3 4 4 4 0 0 0 0 0 0 2 0 3 1 2 3 4 5 6 7 8 9 2 0 0 2 2 8 1 8 5 2 3 6 7 4 1 5 7 5 4 6 8 7 9 8 7 4 5 2 3 6 1 4 5 7 2 5 3 6 5 2 1 2 4 5 8 5 9 9 9 9 6 6 4 5 2 2 3 4 9 1 9 1 1 4 1 4 7 5 2 1 5 0 0 5 6 3 3 2 1 7 7 Example Output 12 14 8 441 Input Explanation Prices of subsets of first test-case 000: 0 100: 0 010: 0 001: 0 110: 2 101: 3 011: 3 111: 4 For the second test-case, each subset costs 0, unless those, which consists of last Tyg3R (and some other) - those cost 2. The third test-case has only one valuable subset (of both Tyg3Rs), which goes on top/right border, and costs 8.
34,247
Math is Love (MATHLOVE) Rashid loves mathematics. He recently started to learn how the various function works in mathematics. On his journey through the math world, he came in touch with a function named Y. He also came to know that, here Y means the summation of number from 0 to n. For example if n = 5, then  Y = 0 + 1 + 2 + 3 + 4 + 5 = 15 Now he is wondering if the knows the value of Y, can he find the value of n for the above equation? Being so very new to the math world, he could not figure out how to approach this new problem. So he came to you for help. Can you help him? Input First line of input will be T (1 <= T <= 100000) , denoting the number of test cases. Next T lines will contain the number Y (1 <= Y <= 3*10^9) , value of the above function. Output For each test case, if there is exist a value of n for which the above function gives the output Y then print that value of n , otherwise print “ NAI ” (quotes for clarification). Note: Data set is huge, use scanf, printf for faster input, output. Sample Input 5 11 15 21 1 7626 Output NAI 5 6 1 123
34,248
Just One Swap (JOSWAP) You are given an array of size N. How many distinct arrays can you generate by swapping two numbers for exactly once? The two selected numbers can be equal but their positions in the array must be different. Input The first line of the input contains a single integer T, denoting the number of test cases. Every test case starts with an integer N. The next line contains N integers, the numbers of the array. Output For each test case output the answer in a single line. Constraints 1 <= T <= 5 1 <= Value of a number in the array <= 100000 2 <= N <= 100000 Example Input: 1 5 2 3 2 3 3 Output: 7 You can generate the following arrays: 2 3 2 3 3 2 2 3 3 3 2 3 3 2 3 2 3 3 3 2 3 2 2 3 3 3 3 2 2 3 3 3 2 3 2
34,249
Simple Path (SIMPLEPATH) You will be given a weighted rooted tree, where root is node 1. For each subtree of that tree, you will have to compute the summation of lengths of all possible simple paths present in that subtree. Eventually you need to print the summation of those values modulo 1000000007 . Image of the tree in the first sample is given below. Input First line of input will contain an integer T (1 <= T <= 10) denoting the number of test cases. Each test case will begin with an integer N ( 1 <= N <= 100000 ), indicating number of nodes. The following N-1 lines will have three integers each, U ( 1 <= U <= N ), V ( 1 <= V <= N ), W ( 1 <= W <= 1000000000 ), which denotes that there is an edge in the tree from node U to node V having W weight. Input File is large. Use fast I/O methods. Output For each test case, print the case number then print the answer to the problem modulo 1000000007 in separate lines. Example Input: 2 7 1 2 3 1 3 2 2 4 1 2 5 4 3 6 6 3 7 8 6 1 2 3 1 3 2 1 4 4 3 5 7 3 6 1 Output: Case 1: 212 Case 2: 109 Explanation of Sample Explanation of the 1 st sample : Summation of lengths of all possible sample paths for each subtree is given below: 1: 174 2: 10 3: 28 4: 0 5: 0 6: 0 7: 0 Explanation of the 2 nd sample : Summation of lengths of all possible sample paths for each subtree is given below: 1: 93 2: 0 3: 16 4: 0 5: 0 6: 0
34,250
Matrix Multiplication 2K (MATRMUL0) Consider the following C++ code, it constructs n×n matrices A,B and vector V from matrix C=A×B which you need to calculate. uint32_t n, i, j, d1, p1, r1, m1, d2, p2, m2, A[n][n], B[n][n]; uint64_t C[n][n], V[n]; //here you need to read n, p1, d1, r1, m1, p2, d2, r2, m2 from input. for (i=0; i<n; ++i) for (j=0; j<n; ++j) { d1 = d1 * p1 + r1; d2 = d2 * p2 + r2; A[i][j] = d1 >> (32 - m1); B[i][j] = d2 >> (32 - m2); } //here you need to calculate C=A*B for (i=0; i<n; ++i) { V[i] = 0; for (j=0; j<n; ++j) V[i] ^= C[i][j]; } //here you need to output V[0], V[1], ..., V[n-1], separated by spaces. Input You are given integers n, p1, d1, r1, m1, p2, d2, r2, m2, separated by spaces. 1≤n≤2048 , 1≤m1,m2≤26, 0≤p1,d1,r1,p2,d2,r2<2 32 . Output You need to output V[0], ..., V[n-1], separated by spaces. Example Input: 4 1664525 0 1013904223 26 1664525 1 1013904223 26 Output: 3929555766216722 770418013451752 7738542081270672 4286515685761206 P.S. There are 4 tests with n≈2048. My best solution time — ~3.2s (~0.8s per test) which is 20 times faster than time limit. Also try the challenge  MATRMUL , to get AC there your time here should be less than 14s for cubic algorithm and 16s for Strassen's.
34,251
Binary Game Reloaded (BG2) Alice and Bob always loves to play different games. One day, they were not finding any game to play and so they were feeling disappointed. Suddenly, they found a book in their room with a binary number written onto it, the length of which was not longer than 100000. Then, They formulate the game rule, say "Binary Game". In this game, the first player chooses a pair of indexes of the binary string and reverses the substring generated by it , so that the string will become lexicographically minimum among all possible selections of indices pairs , and give it to second player. Then, second player do the same thing on the string and give it back to first player. This process continues until there is no way to make binary string lexicographically smaller than before. The player who can not make q move loses the game. Today, Alice and Bob are playing the Binary Game in their room. Suddenly, you enter into their room. Now, Your task is to determine the winner of the game if both of them play in well disciplined manner and the first player of the game is Alice . Input Input starts with an integer T (1<=T<=30) , denoting the number of test cases. Each case contains a binary string probably with leading zeros, which is a binary number in the range of 100000 bit number . Output For each case of input, output the name of the winner of the game. Example Input: 3 00 01 10 Output: Bob Bob Alice
34,252
ShaatChara (GAMEMVS) Meena and Razu have been playing Shaat Chara for many years. But they think the game is too violent. So, they came up with a new game. In this game, instead of just 1 pile, they start with n piles of stones. The game is for two players. Each player takes turn alternatively. In each turn a player can select any of the piles that has at least 1 stone left, and then remove some stone (at least one) from it. The game goes on like this until there are no stones left. The player who can’t make a move loses. At first, Razu was very happy because there was no chance of injury in this game. But he quickly grew frustrated, because Meena was winning all the games. Meena is very clever. She always plays optimally. That means, if there is a chance to win, she will always win. So, Razu came to you with a particular state of the game. He wants to know how many possible moves he may take such that Meena’s win is not guaranteed. Input In a single line, you will be given T, the number of test cases. T test cases follow. In each test case, you will be given n, the number of piles. Then in a single line, you will be given n numbers a i , the number of stones in the ith (1 <= i <= n) pile. Output You have to print the case number first in the form “Case 1: ”. For each case you have to print only the number of winning moves from that particular state of the game. See sample for clarification. T <= 100 1 <= n <= 10000 1 <= a i <= 100000 Note: Note that, winning moves mean the moves that will lead Meena to a losing state. For example, if the current state is {1, 3}, Razu can remove 2 stone from the second pile, which is a winning state. Because this move will lead to the state {1, 1}. Then Meena will remove 1 stone from any pile, and Razu will remove the other in the next turn. And Meena will lose the game, because there will be no remaining stone. But if Razu removed only 1 stone from the second pile, that will lead to the state {1, 2}, which is a winning state for Meena. Thus Meena will win. Example Input: 3 1 1 2 1 1 3 1 1 1 Output: Case 1: 1 Case 2: 0 Case 3: 3
34,253
Fibonacci Polynomial (FIBONOMIAL) The Fibonacci numbers defined as f(n) = f(n-1) + f(n-2) where f0 = 0 and f1 = 1 . We define a function as follows D(n, x) = x + x 2 + 2x 3 + 3x 4 + 5x 5 + 8x 6 + ... + f(n)x n Given two integers n and x, you need to compute D(n, x) since the output can be very large output the result modulo 1000000007 (1e9+7) . Input The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains two integers n and x as described above. Output For each test case, output D(n, x) % 1000000007 in a separate line. Constraints 1 ≤ T ≤ 1000 0 ≤ n ≤ 10 15 0 ≤ x ≤ 10 15 Example Input: 1 7 11 Output: 268357683 Explanation D(7, 11) = 11 + 11 2 + 2(11 3 ) + 3(11 4 ) + 5(11 5 ) + 8(11 6 ) + 13(11 7 ) = 268357683 .
34,254
Highschool Homework (HSHW) Hugo had quite a bad day today. His favourite high school subject, mathematics, was taught by his least liked substitute teacher - he always gave out an abnormally large amount of homework. Today was no different. The teacher wrote N numbers on the board, and after a long thoughtful pause he told the class with a grin: "Well then, kids. For today's homework you will do this harmless exercise. As you can see, I've written quite a few numbers on the board, and your task is to find which two of them have the greatest product. Hm, now that I think about it, that would be too trivial. So you will also have to find which pair of numbers has the greatest quotient. Well, and now that we're at it, why don't you find the pair with the smallest quotient, too. And at that point you might as well find the pair with the smallest product. That should keep you busy for today's evening!". Sigh. How could someone even come up with such a boring, time-consuming and impractical task. If only there was someone who would help Hugo and do it for him. Input The first line of input contains the number 1 ≤ T ≤ 15 : the number of test cases. T cases follow. The first line of each case contains the number 2 ≤ N ≤ 10 5 : how many numbers the teacher wrote on the board. The second line contains N integers; their absolute value will be in the range [1, 10 6 ] (inclusive). In particular, notice that none of them are equal to zero. You may assume that in any input file, the sum of N across all test cases does not exceed 3*10 5 . Output For each case, output five lines. The first one contains the number of the case x in the format "Case x:", starting at 1. Then output four lines, each containing two integers from the input (let's call them x and y ). They need to have the following properties (in this order): x * y is the greatest possible x * y is the lowest possible x / y is the greatest possible x / y is the lowest possible If there are multiple pairs of integers which fulfil the criteria, output the one with the lowest x . x, y may be equal, but in that case their value has to appear at least twice in the input. All four lines are independent, that is the same integer from the input may be used across multiple lines. A number A is said to be greater than B if A > B and lower than B if A < B . Example Input: 1 3 5 -7 10 Output: Case 1: 5 10 -7 10 10 5 10 -7
34,255
University Homework (UNIHW) Hugo had quite a bad day today. His favourite university subject, mathematical analysis, was taught by his least liked substitute teacher - he always gave out an abnormally large amount of homework. Today was no different. The teacher wrote N numbers on the board, and after a long, thoughtful pause he told the class with a grin: "Well then, kids. For today's homework you will do this harmless exercise. As you can see, I've written quite a few numbers on the board, and your task is to find which smallest non-empty subset of them has the greatest product. That should keep you busy for today's evening!". Sigh. How could someone even come up with such a boring, time-consuming and impractical task. If only there was someone who would help Hugo and do it for him. Input The first line of input contains the number 1 ≤ T ≤ 15 : the number of test cases. T cases follow. The first line of each case contains the number 1 ≤ N ≤ 10 5 : how many numbers the teacher wrote on the board. The second line contains N integers; their absolute value will not exceed 10 9 . You may assume that in any input file, the sum of N across all test cases does not exceed 3*10 5 . Output For each test case, first print the string 'Case x: ', where x is the number of the test case, starting with 1. Then print a binary string (consisting of 0 's and 1 's) ; the i th character should be 1 if you decided to include the i th number from the input in the subset. To make the output unambiguous, it should have the following properties: It should contain N characters, at least one of which has to be a 1 . If we multiply the numbers from the input at whose indices this string has the character 1 , the result will be the greatest possible. Out of all binary strings with the above properties, it should contain the minimum number of 1 's. Out of all binary strings with the above properties, it should be lexicographically largest. Reminder: To compare two valid strings lexicographically, find the first position from the left at which they differ. The one with a 1 at this position is lexicographically larger. Example Input: 1 6 -2 -2 -3 4 5 1 Output: Case 1: 101110 The product of the subset this string represents is (-2) * (-3) * 4 * 5 = 120 , which is the greatest possible. It uses the first -2 from the input, as using the second one would result in a lexicographically smaller string. It does not use the 1, as the product would remain the same but the number of 1 's in the string would increase.
34,256
Halum and Candies (HALCAND) Halum has been elected as the captain of his school's football team. To celebrate this, he is going to throw a party. Halum bought candies of N different flavors for the party. There are a i number of candies of the i th flavor where (1 ≤ i ≤ N) . To satisfy a guest he has to give him/her some positive number of candies of at least K different flavors. Otherwise the guest is not satisfied. Given this information now you have to find the maximum number of guests Halum can satisfy with the available candies. Input First line of the input contains an integer T (1 ≤ T ≤ 200) , denoting the number of test cases. T cases follow. First line of each case contains two integers N and K (1 ≤ K ≤ N ≤ 1000) . N space separated integers a 1 , a 2 … a N follow in the next line (0 ≤ a i ≤ 10^9) . The i th of these integers a i denotes the number of candies of i th flavor (1 ≤ i ≤ N) . Output For each case print one line containing " Case X: Y " (without the quotes) where X is the case number starting from 1 and Y is an integer denoting the maximum number of guests who can be satisfied. Example Input: 3 3 3 1 2 3 3 1 1 2 3 3 2 3 2 4 Output: Case 1: 1 Case 2: 6 Case 3: 4
34,257
All in One (ALLIN1) Before you begin, you should try this problem! AVL Tree This problem is simple. Initially, there is a list and it is empty. Then you are given four types of query: Insert data to the list. Remove data from the list. Print an index (1-based) from a specified data after the list was sorted ascendingly. Print data from a specified index (1-based) after the list was sorted ascendingly. Input Input contains several lines. Each line follows one of these formats. 1 n : Insert n (0 ≤ n ≤ 2 31 - 1) to the list. 2 n : Remove n from the list. If n was not found, do nothing. 3 n : Print n 's index (1-based) after the list was sorted ascendingly. 4 i : Print data at i -th index (1-based) after the list was sorted ascendingly (0 ≤ i ≤ 2 31 - 1). -1 : End of input. Output For each query 3, print n 's index in one line. If n was not found, just print -1. For each query 4, print data on i- th index in one line. If the index is not valid, just print -1. Example Input: 3 20 -1 Output: -1
34,258
Januarius, The Travelling Clairvoyant (JAN) The annual Congress of Mages is approaching. Januarius the Clairvoyant intends to participate in it. He has to somehow reach the city where the convention takes place. His favourite means of transportation is railway. He plans to travel using a convenient, direct connection. The train will visit n stations, numbered with consecutive integers. It will depart from station number 1, with station number n as its destination. Remaining stations are intermediate - the train will visit them in order, according to their numbers. Januarius likes travelling by train for a lot of reasons - it's comfortable, you can admire the landscape in peace - but most importantly, tickets are quite cheap. National Railways determined that cost of the trip depends only on the number of sections between stations covered during the ride. Ticket for i sections costs w i . Obviously, the prices become higher when the trip gets longer. You could also travel without a ticket if you're feeling adventurous, but of course there is a risk of unexpected ticket inspection, which can happen during the ride between two consecutive stations. Life of the clairvoyant is devoid of any surprises though - Januarius knows exactly when there will be an inspection. He doesn't have to buy full ticket - it's only important to have valid ticket during the inspection (starting station can be any station before the inspection, and the destination can be any station after the inspection). There are two ways to buy a ticket - from the ticket office at the station, or already on the train, from the ticket inspector. There are limitations though. If you board the train without a ticket, you have to find the inspector immediately after the departure. He only sells tickets starting from the station you boarded the train at. Also, if you boarded the train at the station with a ticket office, you have to pay an additional constant fee of d . Januarius has no time to get off the train during the ride, so he can either buy the ticket at the first station in a ticket office, or at any station from the inspector (he can approach him immediately after the departure from the station and tell him he just boarded the train). Find the cheapest ticket-buying strategy. You must have a valid ticket during every inspection. Input The first line contains a single integer t , denoting the number of testcases. Then, descriptions of the testcases follow. First line of the description consists of three integers n , k and d - number of stations, number of inspections and an additional fee for buying a ticket from the inspector in case there is a ticket office at the station (1 <= n <= 10 6 , 1 <= k <= 1000, 1 <= d <= 10 9 ). In the second line there is a string of length n . If station number i has a ticket office, i -th character of this string is "1", otherwise it's "0". In the third line there are n -1 integers. i -th number w i denotes price of covering i sections. (1 <= w i <= 10 9 , w i < w i+1 ). In the last line there are k integers s i - stations numbers. i -th ticket inspection will take place between the station number s i and the station number s i +1. (1 <= s i <= n -1, s i < s i+1 ) Output For every testcase you should output a ticket-buying strategy that minimizes total cost. Description of the strategy starts with two integers s and b - total cost of the tickets and number of tickets (1 <= b <= n ). Descriptions of the tickets should follow. One ticket description consists of two integers p i and c i - starting station and number of segments for which the ticket is valid. (1 <= p i < n , 1 <= c i <= n - p i ). You should describe b tickets, their total cost must be equal to s , and it has to be minimal. Example Input: 1 5 2 5 11001 2 6 7 10 2 4 Output: 8 2 1 2 4 1 Explanation There are two inspections - between stations 2 and 3, and between stations 4 and 5. Januarius can buy a ticket in the ticket office from the station number 1 to the station number 3, and another one from the inspector from station number 4 to station number 5, and it will cost him 6+2=8. If he bought the first ticket from the second station instead from the first, it would be more expensive - there is a ticket office at the second station, so there will be an additional fee for buying the ticket from the inspector. (2+5+2=9).
34,259
The Idol (IDO) Somewhere in the rainforests of South America, among the deserted ruins, two human figures were carefully traversing through a narrow corridor made of stone. Serpentine vines and thick spider webs, shimmering in the sunlight, were making their journey more difficult. That's not what Archibald the Archelogist was worrying about, though. While Huacho, his companion, was clearing the path with a machete, Archibald was carefully examining the floor. It was covered with square-shaped stone tiles - they were adjacent to each other, and one such tile was as wide as the corridor itself. Some strange looking symbols were carved in the walls near the bottom - seasoned archeologist recognized them at once as La-Og-Mhtir numerals. He studied various records of this civilization for many years now - after all, that's the whole reason he ended up in that jungle in the first place. The journey was taking forever. Archibald was getting increasingly worried - except for a small incident with the natives, everything was going pretty smoothly. He expected deadly traps and hazards at the very least - supposedly no one got ouf those ruins alive. But so far they did not spot anything interesting - apart from that corridor they were traversing. It was tiled with amazing precision and regularity, but the numbers carved above the tiles seemed entirely coincidental. Yet La-Og-Mhtir people were never leaving anything to chance. "Over there, Señor!" shouted Huacho, interrupting Archibald's contemplations. They finally reached the end of the corridor, and found themselves at the entrance to a small, circular room. In the middle of it, a golden figurine in a shape of a human head was placed on the dais. It was also holding a hand near its mouth, which made it look as if it was pondering on something important. "It's The Idol of Ingenuity," said Archibald quietly. "Just like the records said". "No reason to wait, Señor, let's take it and leave!" Huacho rushed in the direction of the dais, and Archibald immediately stopped him. "Careful!" said Archibald quietly, and started looking more closely at the walls. He identified La-Og-Mhtirs' alphabet without difficulty. The inscriptions looked like some kind of warning, and he began to ponder on its exact meaning, but a sudden shout interrupted his thoughts. "Adios, Señor!" His companion was already sprinting through the corridor, with the statuette under his arm. Suddenly, huge spikes launched from under the plate he was standing on, making ear-piercing noise. Archibald winced, but the noise continued. More spikes were appearing at regular intervals from under various plates, while some of them were retracting. The archelogist observed all of this very carefully, but couldn't spot any pattern. Suddenly, he recalled the numbers carved over the plates, and everything became clear. The noise has stopped. Huacho was lying dead on the floor, but apart from that, the corridor was empty. Archibald once again read the warning carved on the wall, gave a thought to it for a moment, and stepped on the first plate with confidence. Input The first line contains a single integer t , denoting the number of testcases. Then, descriptions of the testcases follow. First line of the description consists of two integers n and m (1 <= n <= 10 9 , 0 <= m <= 10 5 ). They denote that the corridor consists of n plates, and the spikes will launch m times in total. Then, m lines follow. One such line consists of two integers p i and c i (1 <= p i <= n , 0 <= c i <= 10 9 ). It means that c i seconds after triggering the mechanism, the spikes will launch from under the plate number p i , counting from the start of the corridor (from the room with the idol). Spikes will retract after one second (unless they are scheduled to launch next second). Every pair of numbers p i , c i appears at most once. The pairs are sorted lexicographically. Output For every testcase you should output one integer in a separate line - the minimal number of seconds that Archibald needs to safely cross the corridor. You should count the time it takes to reach the plate number n , starting from the plate number 1. The mechanism is triggered the moment Archibald steps on the first plate for the first time. Every second, he can decide to go one plate forward, one plate backward or stay in place. One second later he will be at that plate. The journey is safe if for every second, there are no spikes on the plate Archibald is currently standing on (including the last plate). Going back into the chamber with the idol doesn't help, because the mechanism will reset. The mechanism is designed in such a way that it is always possible to cross the corridor. Example Input: 2 3 5 1 1 2 2 3 2 3 3 3 4 3 0 Output: 5 2 Explanation In the first testcase, after stepping on the first plate, Archibald will step on the plate number 2 (because after one second the spikes will launch from under the first plate). Then, he goes back to plate number 1 (after 2 second from the start there will be spikes on the plates 2 and 3, so he cannot go forward or stay in place). Then, he jumps onto plate number two, stays in place, and finally steps on plate number 3. All of this takes 5 seconds. In the second testcase there are no traps, so Archibald can reach the last plate in two jumps. (In this testcase Huacho actually escaped with the idol!)
34,260
Boss Baby (NAJBB) Boss Baby is the boss of all babies. He has been exploring prime numbers lately, and new recently made a conjecture resembling one of Goldbach's conjectures. Boss baby’s conjecture is that any number greater than or equal 10 can be expressed as the sum of a prime, square of two prime. It’s very easy work for him but he is busy to stop the dastardly plot of the CEO of Puppy Co.  He wants your help verify his conjecture for small numbers. Note: 1 is not a prime number. Input The first line of the input contains an integer T (T ≤ 10 6 ) denoting the number of test cases. Each test case will consist of a number greater than 10 and less than 10 6 , one per line. Output For each case, print the case number and the 3 primes P 1 , P 2 , P 3 on a line, where P 1 + P 2 2 + P 3 2 is equal to the number from the input. (P 1 , P 2 , P 3 must be printed in sort order.) If no such primes exist, print "0 0 0" instead (quotes for clarity). If there are multiple triplets of primes that satisfy the equation, print the least one in sorted order. Sample Input: 3 18 20 23 Output: Case 1: 2 3 5 Case 2: 2 3 3 Case 3: 3 3 5 Note For second Case 20 2, 3, 3 (2 + 3 2 + 3 2 ) = 20 2, 3, 7 (2 2 + 3 2 + 7) = 20 are possible, but 2, 3, 3 is the least one
34,261
RPS Warfare (RPSWAR) The Danubian Lowland has always been a very fertile area. No wonder that a long, long time ago there were N kingdoms situated by the Danube river. As all good kingdoms do, each had chosen its favourite weapon, with which it equipped its armies in times of war. The Danube arsenal was quite limited - in these ancient times only three weapons were available: Rocket launchers, Pistols and Swords. An army equipped with rocket launchers devastated those which challenged it with swords. At the same time, they did not stand a chance against opponents using pistols. And as you might already suspect, an army relying on pistols could not withstand the might of a sword-wielding army. Hence, we say that rocket launchers beat swords, swords beat pistols, and pistols beat rocket launchers. Try to guess why the first two paragraphs were dedicated to kingdoms and their weapons. Exactly - these kingdoms constantly fought against each other! Each kingdom went to war with both of its neighbours every year (respectively one, if the kingdom was the left or rightmost). Every war lasted exactly one year, after which the victorious kingdom captured one enemy territory. Of course, just after that another war began. You are given a description of the kingdoms by the Danube river - N characters representing the chosen weapon of each kingdom - in the year 0. Each year, every kingdom will go to war with its neighbouring kingdoms. If two kingdoms a and b go to war, and the weapon of kingdom a beats the weapon of kingdom b , then at the end of the year kingdom a will capture one territory (one character) of kingdom b . If two kingdoms defeat the same territory of a kingdom at once, they decide which one captures the territory by a game of rock-paper-scissors. After some finite number of years, there will only be a single weapon which all the remaining kingdoms are using. Find out which one. Input The first line contains an integer 1 ≤ T ≤ 30 : the number of test cases. T test cases follow. For each case, the first line contains the integer 1 ≤ N ≤ 10 6 - the number of kingdoms by the Danube river. The second line contains N characters representing each kingdom's chosen weapon: R for rocket launchers, P for pistols, and S for swords. The sum of N within one input file does not exceed 2×10 6 .  Warning - the input is quite large. Make sure to read it efficiently. Output For each test case, output "Case x : ", where x is the number of the test case, starting from 1, followed by the character R , P or S : the character representing the weapon which will conquer the entire river bank of Danube. Example Input: 2 3 RPS 7 RRRRRRP Output: Case 1: S Case 2: P In case 1, after the first year the situation will be PSS, and then after the second SSS. In case 2, it will take the pistol-using kingdom six years, but no rocket launcher-equipped kingdom will be able to stop it.
34,262
Fibonacci and Easy GCD (INS17M) The Little Detective and the Kid are tired of fighting with each other, so they try to find the winner by a simple problem. Kid gives the Detective an array A of size N and challenges him to find the following sum : Where Fib (i) is the famous Fibonacci sequence such that Fib (0) =0 , Fib(1) = 1 and Fib(i) = Fib(i-1) + Fib(i-2) for i ≥ 2 . GCD (x, y) represents the greatest common divisor of x and y . Since the answer can be very large, Kid asks Little Detective to find it modulo 1000000007. Help Detective find the answer and tell Kid who is the real artist. Input First line of input contains two space separated integers N and K . Second line of input contains N space separated integers A i . Output: Single integer denoting the value of S modulo 1000000007. Constraints 0 < N ≤ 100000 0 < K ≤ 10 15 0 < A i ≤ 1000000 Example Input: 5 1 2 4 2 1 4 Output: 12
34,263
House Buying Optimizations (HOUSEBUY) Bill and Scott are business rivals. Each of them wishes to buy a house in Javaville, but they want to live as far away from each other as possible. Since Javaville is a relatively new town, there are no maps available yet; instead, information about homes and other buildings has been collected by word of mouth and provided to both Bill and Scott. This information consists of building addresses and distances between buildings. All of the information is consistent, although it may be incomplete or redundant. The streets in Javaville are laid out in a rectangular grid of m east/west streets (named ‘A’, ‘B’, ‘C’ ...) and n north/south streets (numbered ‘0’, ‘1’, ‘2’ ...), where m and n are each between 2 and 10. Every building (either a house or some other building, such as a post office or school) in Javaville is at the intersection of two streets, and no two buildings are located at the same intersection. Some intersections have no buildings at all. All distances are measured in terms of the smallest number of whole blocks that must be traversed north, south, east, and/or west to get from one intersection to another intersection. Here is some sample information that might be provided to Bill and Scott by various reliable sources: There are 5 east/west streets and 5 north/south streets. House1 is located at intersection A0 . The post office is located at intersection A4 . The school is at a distance of 4 blocks from house1. House2 is at a distance of 6 blocks from the post office. The school is at a distance of 6 blocks from the post office. House3 is at a distance of 6 blocks from the post office. From this we can see that there are two possible maps of Javaville — see Figure 1. Figure 1: h1, h2, h3 = houses, P = post office, S = school We see that the locations of house1, the post office, and the school are fixed, but house2 could beat either C0 or E2, and house3 could be at either C0 or E2. Clearly there is always a pair of houses separated by 6 blocks (house1 is always 6 blocks from the furthest house), but the best distance we can guarantee for any specific pair of houses is 4 (since house2 is always 4 blocks away from house3). We would report this information to Bill and Scott, telling them that, even though a separation of 6 is always achievable, the safest recommendation that we are able to make for specific houses is to have one of them purchase house2 and have the other purchase house3. (We assume that Bill and Scott will consult with one another before purchasing their houses in order to guarantee that one of our recommendations is followed.) Bill and Scott would like you to write a program that will take location and distance information about buildings and determine two quantities, D and D . D is the minimum, over all possible valid arrangements of buildings, of the largest house separation in each arrangement. D is the maximum value for which there exists at least one pair of houses i and j that are guaranteed to be separated by a distance of at least D′ . In the latter case, you should list all pairs of houses that are guaranteed to be separated by at least D blocks. More precisely: Define the diameter d(S) of a feasible urban layout S as the distance between the two most distant residential homes in the layout. For the two residential houses i , j , define their safety factor: e[i, j] is defined as the minimum value of the distance between residential houses i and j in all feasible urban layouts. Bill and Scott want you to write a program that calculates D and D' based on the information they collect, where D = min {d (S)} over all layouts S ; D' = max {e[i, j]} over all pairs (i, j) . At the same time you also have to give the safest purchase recommendations: that is, all pairs (i, j) meeting e[i, j] = D' for residential houses i and j . For the above example, the first layout has d(S1) = 6, while the second layout has d(S2) = 6. The safety factor between each two residential houses is respectively: e[1, 2] = 2, e[1, 3] = 2, e[2, 3] = 4. Then: D = min {d (S1), d (S2)} = 6, and D' = max {e[1, 2], e[1, 3], e[2, 3]} = Purchase recommendations are: house 2 and house 3. Input The input will consist of one or more descriptions. Each description will begin with a line containing two positive integers, m and n , representing the number of blocks in each direction (2 ≤ m, n ≤10). Each description will end with a line containing the single word ‘ END ’ in uppercase. The entire data set will end with a line containing a pair of zeros. The remaining lines in each data set will be in one of the following two formats: name LOCATION r c      or name DISTANCE d name2 where name and name2 are strings containing only digits and lowercase alphabetic characters, each of length at most 10; r is an uppercase letter between ‘A ’ and ‘J ’; c is a digit; and d is a positive integer. If the first five characters of a name are the lowercase letters ‘house ’ then it is a candidate for selection as a home for Bill or Scott; otherwise it stands for some non-residential building. In a ‘ DISTANCE ’ specification, name2 will always be the name of some building that has occurred previously in this data set as the first name on one of the data lines (in other words, there are no forward references to buildings in ‘ DISTANCE ’ constraints). Each description is consistent (i.e., there is at least one way to lay out the houses and other buildings in a way consistent with the description). Each description will include information about at least two distinct houses. At most 25 distinct building names will occur in each description, and there will be at most 50 constraints ( ‘LOCATION ’ or ‘ DISTANCE ’) for each description. Output For each description, the output will consist of D , followed by value of D' , and then a list of all pairs of houses with maximum guaranteed separation D′ (which might be smaller than the maximum achievable separation). No pair of houses should be listed more than once. The output should be labeled exactly as shown in the sample output below, with a blank line separating the outputs for consecutive data sets. In each pair, houses should be ordered according to the first time they appear in the input; the list of pairs should be ordered in the same way, sorted by the first element of the pair, then by the second element. Example Input: 5 5 house1 LOCATION A 0 postoffice LOCATION A 4 school DISTANCE 4 house1 house2 DISTANCE 6 postoffice school DISTANCE 6 postoffice house3 DISTANCE 6 postoffice END 10 10 house1 LOCATION A 0 building2 DISTANCE 12 house1 building2 DISTANCE 12 house1 house3 DISTANCE 7 house1 building4 DISTANCE 2 house3 building4 DISTANCE 7 building2 building4 DISTANCE 2 house3 house5 DISTANCE 6 building4 building6 DISTANCE 10 building2 building6 DISTANCE 5 building4 building6 DISTANCE 2 house1 house7 DISTANCE 1 house1 house7 DISTANCE 1 house1 building8 DISTANCE 10 house7 house9 DISTANCE 10 building2 house9 DISTANCE 3 building4 building10 DISTANCE 5 house3 building10 DISTANCE 5 house3 house11 DISTANCE 3 building2 building12 DISTANCE 7 house7 building12 DISTANCE 8 house1 building12 DISTANCE 9 building4 building12 DISTANCE 3 house5 house13 DISTANCE 7 building8 house13 DISTANCE 3 house5 building14 DISTANCE 2 building10 building14 DISTANCE 9 building8 house15 DISTANCE 12 building8 house15 DISTANCE 11 building12 house15 DISTANCE 9 building2 house15 DISTANCE 7 house13 building16 DISTANCE 6 building10 building16 DISTANCE 3 house11 building16 DISTANCE 12 house9 building16 DISTANCE 5 house7 house17 DISTANCE 4 house11 house17 DISTANCE 3 building12 building18 DISTANCE 8 building14 building18 DISTANCE 10 building6 building18 DISTANCE 8 building14 building18 DISTANCE 10 building6 house19 DISTANCE 2 house13 house19 DISTANCE 6 building18 house19 DISTANCE 1 house5 building20 DISTANCE 8 building14 END 0 0 Output: 6 4 house2 house3 9 9 house1 house11 house5 house9 house9 house11 house9 house17
34,264
If Chain (IFCHAIN) Consider the following code: if (a) if (b) if (c) foo(); where a, b and c  are boolean variables. If we run this code in C++, the function foo() is called if and only if all three variables are true. However, recently a new language - C-- - is being developed. In this language, when an if() evaluates to false, only the statement directly following it is not executed; for example, if a was false, the program would jump from if(a) to if(c) . Using this convention, there are 5 different possible assignments of truth values to the variables a , b , c  which end up calling foo() . Considering a , b , c  as three bits in that order, they are 111, 101, 100, 011 and 001. Given n boolean variables within a chain of m   if() 's, where the variables within one if() are separated using logical or , count the number of ways to assign truth values to them which end up calling the function foo() (the call to foo()  is after the last if() ). Input The first line of the input is the number of test cases 1 ≤  T ≤ 30 . T test cases follow. The first line of each test case contains two nonnegative integers n ≤ 10 5  - the number of boolean variables (they are numbered 1 through n ) - and m ≤ 10 5  - the number of if() 's. m lines follow, the i -th line describing the i -th if() . The first integer in each line is a positive integer k i  - the number of variables in the i -th if()  (implicitly separated by the logical or  operator) - followed by  k i positive integers in the range [1,n] : the variables in the i -th if() . Not all variables need necessarily appear within the if() chain, and the variables within one if()  need not be distinct. The sum of k i within a test case will not exceed  5*10 5 . Additionally, the sum of n , m and k i   within a single input file will not exceed 2*10 6 . The input is quite large - make sure to read it efficiently. Output For each case, output the string "Case x : y " in a single line, where x  is the number of the test case, starting from 1, and y is the number of ways of assigning truth values to the n boolean variables (out of 2 n ), which when run in C-- end up calling foo() , modulo 10 9 +9 . Example Input: 2 3 3 1 1 1 2 1 3 5 3 2 1 2 3 1 3 5 2 2 4 Output: Case 1: 5 Case 2: 24
34,265
Paragliding Trip (PARAG) Ever heard of paragliding? It's a recreational sport in which one jumps off an elevated position, and then soars through the sky equipped with a 'paraglider' (a parachute of sorts). Although air currents might help you out, gravity will relentlessly pull you towards the ground eventually. As all good sports, paragliding has a group of enthusiasts in Slovakistan, who call themselves 'Klub Slovakistanských Paraglidistov' (KSP). And as all real enthusiast groups, KSP organizes club activities - group tours to the most prestigious paragliding centers, where all members of the club can paraglide to their hearts' content in the most luxurious mountain ranges. Of course, every upcoming tour must be more awesome than the last, and so the selection of the right destination is key. It will be extra important this year, as the Slovakistan paragliding superstar Syseľ agreed to come along. With his dedication and love for the sport, he is recognized on the worldwide paragliding scene. In his bestseller autobiography the members of KSP have read that Syseľ enjoys long flights the most - such that the difference of the heights of the mountain he jumps from and lands on is greater than m . In the context of an exclusive interview he mentioned that what he most dislikes about paragliding is the need to climb up onto a mountain after every jump; hence, he usually likes to jump from a tall mountain, land on a smaller one, and immediately jump again from this smaller mountain, and so on. If he does this s-1 times, he is satisfied. Lastly from an intercepted phone call KSP members concluded that Syseľ likes to paraglide after lunch, but only in the eastwards direction, as when he paraglides to the west the sun shines into his eyes. KSP does not want to disappoint Syseľ, and hence they are looking for such a mountain range which has the most possible trips which satisfy Syseľ. Help them! Task Every mountain range consisting of n mountains can be described as an array of n numbers, representing the heights of these mountains from west to east. A trip is an arbitrary sequence of several, not necessarily neighbouring mountains, which satisfies Syseľ if and only if it contains exactly s mountains, and between each two consecutive mountains in this sequence the difference in elevation is greater than m - that is if a mountain's height is x , and the nearest mountain to the east on the trip has a height of y , then x-y>m . For a given mountain range consisting of n mountains and the values of m and s , find the number of trips which exist in this mountain range that satisfy Syseľ. Input There are multiple test cases - their number  1 ≤ T ≤ 70  will be on the first line. The first line of each test case contains the integers 1 ≤  n ≤ 10 5 , 0 ≤  m ≤ 10 18  and 2 ≤  s ≤ 20 : the number of mountains in the mountain range, the required difference in elevation, and the number of mountains in a trip which satisfies Syseľ. The second line of each test case contains  n numbers - the heights of the mountains in the mountain range, from west to east. The heights of mountains are positive integers not greater than 10 18 . The sum of n  within one input file does not exceed 400,000 . Output For each test case output the string "Case x : y ", where x is the number of the test case, starting from 1, and y is the number of trips in the mountain range that satisfy Syseľ, modulo 10 9 +7 . We consider two trips distinct if there exists at least one mountain which belongs to one trip but not the other. Example Input: 3 4 0 2 5 4 3 1 4 1 2 5 4 3 1 8 3 3 11 15 15 10 10 7 1 1 Output: Case 1: 6 Case 2: 4 Case 3: 14 In the first case, any pair of mountains is a trip which satisfies Syseľ. In the second case, the pairs of mountains with heights (5,4) and (4,3) no longer have a great enough elevation difference.
34,266
Those College Days! (IIITD1) Once there was a Shikaari in IIIT Delhi campus and he was famous for his Shikaar techniques. Also there was Kalakhatta who was jealous of Shikaari’s charisma. Once Kalakhatta challenged Shikaari to test his knowledge. Now Shikaari’s afraid of losing, would you help? You are given a number N and you have to increment the most significant digit without changing any other number in N. You can do this by adding a positive number X. Input The first line of the input consist of a single integer number T which determines the number of tests. In each of next t lines there is a single integer number N. Constraints 0 < t ≤ 10 5 | n | ≤ 10 9 Output Print the minimum number X in separate lines. Example Input: 2 5 15 Output: 1 10
34,267
SLIS (QUERYIT) Rachit, Sandeep, Yogesh, Vikram and Shubham are very good friends. They participated in a contest MNNIT INSOMNIA as a team but there was a problem which was not solved by any of the teams. So they were desperate to solve that problem. After the contest they asked you for your help to solve the problem. Help them to solve the problem. The problem is as follows: There is an array of length n consisting of only 0 and 1 as elements. You have to answer q queries. There are two type of queries: Type 0: There is l and r. You have to change each 0 to 1 and each 1 to 0 from l to r (both inclusive). Type 1: print the length of longest non decreasing subsequence of the array. Note : Indexing is 1 based. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Input First line consists of two integers n and q where n is length of array and q is number of queries. Second line consists of array of length n without spaces. After that there are q lines containing type of query. And for type 0 query it has two integers l and r. 1<=n,q<=10^5, 1<=l<=r<=n Output Print a single line for each query of type 1 containg length of longest non decreasing subsequence. Example Input: 5 5 10111 1 0 3 5 1 0 2 3 1 Output: 4 4 3
34,268
Urdhva - Tiryag Bhyam (URD) Given two large digit numbers find their product. Input 1st line contain number of test cases T. Each of which followed by two numbers N1 and N2 (these are strings). 1<=T<=10^5,  1<=|N1|<=1000 & 1<=|N2|<=1000 Output For each test case print product of these two numbers in separate line with no leading zero values. Example Input: 2 6 9 9 2 Output: 54 18
34,269
NEO (NEO2) Given array with n integer elements. We divide it into several part (may be 1), each part is a consecutive of elements. The NEO value in that case is computed by: Sum of value of each part . Value of a part is sum all elements in this part multiple by its length. Example: We have array: [ 2 3 -2 1 ]. If we divide it look likes: [2 3] [-2 1]. Then NEO = (2 + 3) * 2 + (-2 + 1) * 2 = 10 - 2 = 8. Because there are many ways to divide an array into several part, so we can get many of NEO value. Your task is find the NEO with maximum value. Input First line: T (number of test case, T <= 10) For each of testcase: + First line: n (1 <= n <= 10^5) + Second line: a[1], a[2], ..., a[n] (-10^6 <= a[i] <= 10^6) Output Each testcase print the Example Input: 1 4 1 2 -4 1 Output: 3
34,270
Ada and Power (ADAPOWER) Ada the Ladybug got a new homework today. She was attending algebra class and teacher was lecturing about various utilizations of matrix multiplication. He wanted to teach his students about the power of matrix, so he gave them following homework: Students were given a matrix followed be multiple queries. The query of first kind is adding a number to each element of a rectangular region of their matrix. In the query of second kind, a matrix is given and students are asked, whether it is the second power of actual matrix. Can you help Ada to solve her homework? Input The first line contains two integers 1 ≤ N ≤ 150 , the size of square matrix and 1 ≤ Q ≤ 200 , the number of queries. Each of the next N lines contains N integers 0 ≤ A x, y ≤ 100 , the element on x th ,y th coordinate of matrix. Then Q queries follows: The query of first kind is 1 followed five integers 0 ≤ x, y ≤ X, Y < N , specifying the part, to which the number will be added, and number 0 ≤ V ≤ 100 , the value which will be added. The query of second kind is 2 followed by N lines containing N integers, which are supposed to be the second power of actual matrix. Output For each query of second kind, print either yes , if given matrix is second power of actual state of matrix or no in the other case. Example Input 2 5 1 2 2 1 2 5 4 4 5 2 4 5 5 4 1 0 1 1 1 1 2 7 9 6 10 2 5 4 4 5 Example Output yes no yes no Example Input 2 5 10 66 60 69 84 23 69 81 94 91 66 24 38 35 65 28 31 27 91 57 11 4 5 40 0 71 1 3 0 4 0 79 2 21301 13825 21173 20277 9967 27887 17060 26586 24464 15252 14519 7743 13488 11454 6743 18490 13839 18940 20861 8268 12676 7260 10437 10027 8400 1 1 0 4 2 100 1 2 4 3 4 37 1 2 2 2 2 1 1 0 2 0 3 4 2 46237 38485 46414 21029 16080 96987 88160 100456 49140 37497 73915 66266 75834 36015 28535 79761 74224 83550 45701 31771 60176 56760 62709 34759 25280 2 46237 38485 46414 21029 16080 96987 88160 100456 49140 37497 73915 66266 75835 36015 28535 79761 74224 83551 45701 31771 60176 56760 62709 34759 25280 2 46237 38486 46414 21028 16080 96987 88160 100456 49140 37497 73915 66265 75835 36016 28535 79761 74224 83551 45701 31771 60176 56760 62709 34759 25280 2 46237 38485 46414 21029 16080 96987 88160 100456 49140 37497 73915 66266 75835 36015 28535 79761 74224 83551 45701 31771 60176 56760 62709 34759 25280 Example Output 2 no no yes no yes
34,271
THE SHORTEST PATH (ALCATRAZ4) You are given a 2D grid with each cell containing a letter, you have to start at any point and move either up, down, left and right to create the word "ALCATRAZ" by picking up letters in order . After choosing a letter, it gets removed and leaves the cell empty. You have to determine the minimum number of moves needed to do so. Input 2 space separated integers N, M (number of rows and columns respectively.) 1 ≤ N, M ≤ 500 Then next N lines gives the details of the maze. Output The shortest path as described in the above problem. Print "IMPOSSIBLE" (without quotes) if you can't make that word. Example Input: 4 5 AZCLT AARAL SJATC LARAZ Output: 9 Path is as follows: 2, 4 → 2, 5 → 3, 5 → 3, 4 → 3, 3 → 3, 4 → 4, 4 → 4, 3 → 4, 4 → 4, 5
34,272
Ada and Birthday (ADAGIFT) Even though there is almost half a year before Ada the Ladybug's birthday, her friend already started searching for a birthday gift. As Ada is a mathematician, they decided to give her a number. They know that Ada loves numbers, which are composed by concatenation of prime numbers (at least one). Sometime there are multiple ways to do so: for example 37 can be concatenation of "3" and "7", yet it can also be concatenation of "37" itself. The more ways, the better the number is. Ada's friends want to surprise her by as good number as possible so they want you to write a program, which could count the number of ways. NOTE: Number with leading zeroes is a valid number (treat it as if the leading zeroes are not there) Input The first line contains an integer 1 ≤ T ≤ 100 Each of the next N lines contains a number 1 ≤ A < 10 30 Output For each number, print the number of ways it can be written as concatenation of prime numbers. Example Input 8 2 37 111 3737 133 1000000009 113731191937237 1111111111111111111111 Example Output 1 2 0 6 1 1 197 1
34,273
Ada and Scarecrow (ADACROW) As you might already know, Ada the Ladybug is a farmer. She has multiple farmhouses and some fields which always connect two adjacent farmhouses. She plans to buy some scarecrows to scare crows! A scarecrow placed on a farmhouse scares all crows from all adjacent fields. A crow on a field can be disastrous, so Ada has to arrange the scarecrows in such way that they cover all the fields. As scarecrows are pretty expensive she wants to minimize the number of them. Can you count it for her? Note: Even thought it might look like that from description, the formed "graph" doesn't have to be planar! Also multi-fields and self-field are not allowed. Input The first line contains an integer 1 ≤ T ≤ 100 Each of the next T test-cases begins with two integers 0 ≤ M ≤ 150, 1 ≤ N ≤ 150 , the number of farmhouses and the number of fields. Each of next M lines contains two numbers 0≤ A i ,A j < N , the farmhouses, which are connected by a field. Output For each test-case output the minimal number of scarecrows Ada has to buy, to cover all fields. Example Input 6 3 3 1 2 1 0 2 0 4 3 1 2 1 3 1 0 5 6 0 2 0 3 1 3 1 2 1 4 2 4 5 8 0 1 0 3 0 4 1 2 1 4 3 4 3 2 2 4 4 2 0 1 2 3 6 9 0 4 4 3 1 2 2 0 2 3 5 3 4 1 4 2 5 0 Example Output 2 1 3 3 2 3 Example Input 2 2 17 7 12 9 11 8 9 16 11 2 5 14 7 6 8 14 16 23 10 13 11 3 7 14 14 3 9 11 7 8 0 9 8 14 10 8 0 4 6 15 6 12 2 5 10 2 7 11 13 12 15 13 5 3 15 0 6 2 12 9 5 1 1 4 Example Output 2 4 9
34,274
Ada and Tulips (ADASEED) As you might already know, Ada the Ladybug is a farmer. She decided to plant two similar rows of of tulips. She bought 2×N seeds of L different colors and planted them (in both rows) in such way, that the tulip of some color was L units far from nearest tulip of the same color. As Ada is also a mathematician, she gave you a more formal description: The i th position had color i % L (where % stands for modulo). Even though she tried hard, she didn't expect the power of nature. A hurricane appeared and permuted the seeds in both rows (each seed remained in the same row, but got possibly different position in it). Now the tulips grew but the rows doesn't have the same sequences of colors. Ada doesn't like that, so she wants to rip off the least number of tulips so that both rows will have same sequence of colors. Input The first line contains an integer 1 ≤ T ≤ 1000 , the number of test-cases. Each of the next T test-cases begins with two integers: N, L ( 1 ≤ L ≤ N ≤ 2×10 5 ), the number of tulips and the number of colors. Each of next 2 lines will contain N integers 0≤ A i < L , the colors of tulips. As Ada likes diversity, so she also assures you that N/L (integer division) won't exceed 100 . The sum of N over all test-cases won't exceed 10 6 Output For each test-case output the minimal number of tulips, which has to be ripped to achieve same sequences Example Input 4 4 4 1 2 3 0 0 3 2 1 5 2 0 1 1 0 0 1 1 0 0 0 3 1 0 0 0 0 0 0 6 3 0 0 1 2 2 1 1 2 0 2 0 1 Example Output 6 2 0 4
34,275
Ada and Party (ADAPARTY) Ada the Ladybug is already planning her birthday party. It is not an easy process since she have many friends but each of her friends likes just about half of her other friends. She wants to invite only such subset of friends that everyone likes each other. Ada has barely some time and she wants big party so she asked you to find maximum such list in which each of her friends is friend with each of her other friends on the list. Input The first line contains an integer 1 ≤ T ≤ 100 , the number of test-cases. The first line of each test-case begins with 1 ≤ N ≤ 130 , the number of her friends. Each of next N lines contain N integers A i,j (either 0 or 1 ), where 1 means the i th friend likes j th (and 0 means the opposite) Important note is, that as brain connections of insect are not so complicated as those of humans, so the process of making friends is slightly different. Two insects have exactly 50% chance of being friends, so also the adjacency matrix will be generated (very)pseudo-randomly with 50% chance for each edge. Also note, that the matrix will be symmetrical. Each insect is friend with itself! Output For each test-case output the maximum number of Ada's friends, which can be invited. Example Input 10 7 1 1 0 0 1 1 0 1 1 1 0 1 1 0 0 1 1 0 1 0 1 0 0 0 1 0 0 1 1 1 1 0 1 1 0 1 1 0 0 1 1 0 0 0 1 1 0 0 1 5 1 1 1 1 0 1 1 1 0 1 1 1 1 1 0 1 0 1 1 0 0 1 0 0 1 1 1 4 1 0 0 1 0 1 0 1 0 0 1 0 1 1 0 1 1 1 10 1 1 0 1 0 1 0 1 1 1 1 1 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 1 0 0 0 0 1 1 0 0 0 1 1 1 0 0 1 0 1 0 1 0 0 0 1 0 1 0 0 1 0 1 1 1 0 0 0 0 1 0 1 1 1 1 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 1 1 0 1 7 1 1 0 1 1 0 0 1 1 1 0 1 0 0 0 1 1 0 0 1 0 1 0 0 1 1 0 0 1 1 0 1 1 0 1 0 0 1 0 0 1 0 0 0 0 0 1 0 1 3 1 1 0 1 1 1 0 1 1 8 1 0 1 1 1 1 0 0 0 1 0 1 1 1 1 1 1 0 1 1 0 1 0 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 1 1 6 1 0 1 0 0 1 0 1 0 0 0 1 1 0 1 1 1 0 0 0 1 1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 Example Output 4 3 1 2 1 3 3 2 4 2
34,276
Ada and Parties (ADAPARTI) Ada the Ladybug is already planning her birthday party. It is not an easy process since she has many friends. At first, she had a plan to invite only subset of her friends but now her plans are different. She wants to satisfy all her friends so she is going to hold multiple parties. Anyway she wants to satisfy fact, that each of her friends will have all of their friends at the same party while there will be no one, who is not his/her friend. Problem is, that with current layout, it might not be possible. It is not so easy to let two bugs become friend, and it is not so "nice" to make them enemies... yet both are possible. Ada asked you to find the minimal number of such operations so that the parties will be possible! Ada doesn't want to do many of such operations so she already made a little research and found out she won't need more than 12 such operations. Input The first line contains an integer 1 ≤ T ≤ 100 , the number of test-cases. The first line of each test-case begins with 1 ≤ N ≤ 62 , the number of her friends. Each of next N lines contain N integers A i,j (either 0 or 1 ), where 1 means the i th friend likes j th (and 0 means the opposite) Note, that the matrix will be symmetrical. Each insect is friend with itself! Output For each test-case output the minimal number of introductions and antagonizations. Example Input 7 7 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 1 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 0 0 0 1 8 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 8 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 1 0 0 0 0 0 1 3 1 0 0 0 1 0 0 0 1 7 1 1 0 0 0 1 0 1 1 0 0 1 0 1 0 0 1 1 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 1 1 0 1 1 0 0 1 1 6 1 1 1 0 0 0 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 1 0 0 0 1 0 0 1 1 0 1 0 0 1 1 5 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 Example Output 2 4 1 0 4 2 2
34,277
Ada and Connections (ADACON) Ada the Ladybug was on a trip with her friends. They each bought a souvenir there. As all of them are mathematicians, everybody bought a number. They want to modify the numbers to have some connection between each other. They have decided to modify the numbers so they would have their GCD greater than 1 ( gcd(a 1 ,a 2 ,a 3 ,...,a N )>1 ). Anyway it is not easy to change a number - the only thing they can do is to go to a professor in mathematics, which could forge a number A into number A+1 or A-1 . As this operation is not cheap, they want to minimize number of such operations. A number might be forged any number of times. NOTE: gcd(a,0)==a (so gcd of two 0 is also 0) Input The first line contains an integer 1 ≤ N ≤ 3*10 5 , the number of friend who were on trip (and also the number of numbers). The second line contains N integers 0 ≤ a i ≤ 10 6 Output Print a single line with minimum number of operations to make a connection between all numbers. Example Input 5 3 9 7 6 31 Example Output 2 Example Input 2 9 3 4 5 7 8 9 11 12 13 Example Output 2 6 Example Input 3 5 7 7 11 17 1 Example Output 3 5
34,278
Harbinger vs Sciencepal (R6PL) Rainbow 6 is a very popular game in colleges. There are 2 teams, each having some members and the 2 teams play some matches against each other. The team which wins the maximum number of matches wins the game! Two of my friends Ashank and Aditya (better known as Harbinger and Sciencepal) are great gamers and they want to compete. So they decide to form their own teams. There are 2×N players who are interested to be a part of their team. Each player has some rating (based on his performance) and Akarsh (Nimbus) is responsible for forming their teams. Being a good friend of both, he wants to form two teams such that the difference of total ratings of the players between the teams becomes minimum. The players come to him in pairs and he has to put one of them in Harbinger's team and the other in Sciencepal's team at that instant. This is a tedious task for him and therefore he needs your help! Input The first line of the input contains an integer  T  denoting the number of the test cases. (1 ≤ T ≤ 10) First line of each test case contains a number  N  denoting the number of pair of players. (1 ≤ N ≤ 200) Next  N  lines contains rating of the persons in pairs as  x  and  y . (0 ≤ x, y ≤ 2500) Output For each test case, print a single integer denoting the minimum possible absolute rating difference between Sciencepal's and Harbinger's team. Example Input: 1 2 2 3 4 5 Output: 0
34,279
Ada and Taxes (ADATAXES) As you might already know, Ada the Ladybug is a farmer. She grows vegetables in a long furrow. All of the vegetables have some height. Local politicians tax small vegetables, but as the furrow is very long, they always tax just a part of it. The taxes always have some limit on height. They are calculated very simply: Tax collectors multiply the heights of all vegetables, which are lesser or equal to limit and are on desired segment. The taxes might be very high so tax collectors just round their income and take only 1000000007 ( 10 9 +7 ) banknotes. They are very kind, so they always leave the rest to Ada. She is interested in how much they will leave her. NOTE: If none of the vegetable is lesser/equal to given limit, Ada is left with symbolical 1 "money". Input The first line contains an integer 1 ≤ N, Q ≤ 3*10 5 , the number of vegetables Ada grows and the number of times the tax collectors come. The second line contains N integers 1 ≤ A i ≤ 3*10 5 , the heights of vegetables. The next Q lines contains three integers 0 ≤ L ≤ R < N , the left and right vegetables of segment and 1≤ H ≤ 3*10 5 , the limit. Output Print a single line for each query with the number of money Ada will be left with after each tax collecting. Example Input 10 6 1 2 3 4 5 10 9 8 7 6 5 5 5 0 2 3 0 9 9 4 8 8 2 4 11 2 2 3 Example Output 1 6 362880 280 60 3
34,280
Save Lord Tachanka (TACHANKA) Our friend Lord Tachanka is on an important mission. He has to reach basecamp quickly. But the evil enemies have stolen many LMGs and have placed them along the way. You'll have to help him out! Lord Tachanka is initially at the top left corner (1, 1) of a rectangular N × M grid. He needs to reach the bottom right corner (N, M). He can only move down or right. He moves at the speed of 1 cell per second. He has to move every second—that is, he cannot stop and wait at any cell. There are K special cells that contain the LMG planted by the enemies. Each LMG has a starting time t and a frequency f. It first fires at time t seconds, followed by another round at time t+f seconds, then at time t+2f seconds …. When a LMG fires, it simultaneously emits four bullets, one in each of the four directions: up, down, left and right. The pulses travel at 1 cell per second. Suppose a LMG is located at (x, y) with starting time t and frequency f. At time t seconds, it shoots its first set of bullets. The bullets travelling upwards will be at the cell (x,y-s) at time t+s seconds. At this time, the bullets travelling left will be at cell (x-s, y), the bullets travelling right will be at cell (x+s, y) and the bullets travelling down will be at cell (x, y+s). It will fire next at time t+f seconds. If a bullets crosses an edge of the grid, it disappears. The LMGs are numbered 1 to k, and if two bullets from different LMGs happen to meet, the one coming from the higher numbered LMG survives. At any time, if Lord Tachanka and a bullet are in the same cell, he dies. That is the only way bullet interact with Lord Tachanka.  But don't be worried, as you can help the Lord. He can contact his basecamp and can report them the exact position of an LMG, and it will be destroyed by air support. But the war is going on, and you as a commander will have to ensure that minimum missiles are wasted. Given these, you should find the least time (in seconds) in which Lord Tachanka can reach his basecamp safely. Also calculate the minimum number of LMGs that need to be destroyed so that the Lord can reach the basecamp safely. Constraints 2 ≤ N, M ≤ 500 1 ≤ K ≤ 500 All the frequencies are guaranteed to be integers between 1 and 600, inclusive. All the starting times are guaranteed to be integers between 0 and 600, inclusive. All the coordinates of the LMGs are guaranteed to be valid cells in the N×M grid. No two LMGs will be on the same cell. Input Line 1: Three space separated integers N, M and K, describing the number of rows and columns in the grid and the number of LMGs, respectively. Lines 2 to K+1: These lines describe the K LMGs. Each line has four space separated integers.  The first two integers on the line denote the row and column where the LMG is located,  the third integer is its starting time, and the fourth integer is its frequency. The LMGs are numbered in the order in which it appears in the input, i.e. from 1 to k. Output You need to output two integers, the minimum amount of time required for the Lord to reach the basecamp, and the minimum LMGs needed to be destroyed. Example Input: 4 4 1 3 2 1 3 Output: 6 0
34,281
Ada and Greenflies (ADAGF) As you might already know, Ada the Ladybug is a farmer. Beside of growing vegetable she also breeds greenflies. There are many kinds of greenflies and it is not trivial to breed them since they behave very strangely. Each kind of greenfly is known under a number. As you have multiple greenflies in a single coop, they produce as much juice as the greatest common divisor of their numbers. Ada owns a row of greenflies (of several kinds) and she can split them by a fence, so that always a continuous segment of greenflies will be in a same coop Ada wants to find out the sum of production of greenflies over all possible continuous segments (of size at least one), can you help her? Input The first line contains an integer 1 ≤ N ≤ 3*10 5 , the number of greenflies in row. The second line contains N integers 0 ≤ a i ≤ 10 6 Output Print a single line: the sum of production of all continuous segments. Example Input 5 2 2 3 6 2 Example Output 29 Example Input 2 7 2 4 6 12 18 6 4 Example Output 2 118 Example Input 3 5 2 4 8 16 32 Example Output 3 114 Example Input 4 4 12 20 20 5 Example Output 4 96
34,282
The Permutation Game Again (TPGA) Since YoMamaSoFat was able to answer Blackhood's and Kira's question as in TPGAME (though with a little help from your side), it was my turn to ask him a question. This would again be a coding question as you might be knowing he is a noob in coding. I gave him a permutation of N distinct integers from 1...N and asked him the rank of the permutation when all possible permutations of the integers are arranged lexicographically. For example, for N = 3, all possible permutations arranged lexicographically would be:- 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 From the above, rank of 1 2 3 would be 1, rank of 1 3 2 would be 2 and so on. HELP HIM! NOTE:- You may assume it is the same permutation which Blackhood gave him in TPGAME to tell the number of inversions for each integer in it. Input First line of the input contains t, the number of test cases (1 ≤ t ≤ 10). 2×t lines follow, two for each test case. Each test case begins with an integer N, the number of elements in the permutation (1 ≤ N ≤ 200000). The next line contains N space separated distinct integers from 1...N, representing the permutation. Output For each test case, print the rank of permutation %1000000007 on a new line. Example Input: 3 1 1 3 3 2 1 4 2 1 4 3 Output: 1 6 8
34,283
Chessboard State 1: National Chess Tournament (CSTATE1) Note: This is an easier version of the problems CSTATE2 and CSTATE3. A solution to those problems (except the I/O format) will pass here.   The inhabitants of Slovakistan decided to organize a national chess tournament. Since the first place prize is 1 point on SPOJ, everyone played as if their life was at stake. However, since time was not measured in this chess tournament (unlike at most chess tournaments in the rest of the world), a problem occurred - players took way too long to admit defeat. They always just kept thinking and thinking, trying to find some move which would prevent their king from being taken. Just one more moment... And perhaps one more... The inhabitants of Slovakistan are planning to hold the tournament next year as well. It would be great if a skilled programmer lent them a hand and got rid of this nuisance! For a given description of a chessboard, decide its state - which player's king is under threat, and whether it is a Check or a Checkmate. For the purposes of this problem only take into account basic moves of every chesspiece; complicated moves such as Castling, En passant, moving a pawn 2 squares or Promotion are not accepted in Slovakistan. Input The first line of the input contains the integer 1 ≤ t ≤ 2000  - the number of chessboards. t descriptions of a chessboard follow. Each description of a chessboard consists of 8 rows, each consisting of 8 characters (the chessboard is of the traditional dimensions 8x8 ). These characters are from the set {.KQRBHPkqrbhp} , representing in this order an empty square, king, queen, rook, bishop, knight (horse), and pawn. The pieces belonging to the White player are marked by lowercase characters; the upper side of the chessboard (first in the input) belongs to him, hence white pawns move downwards. The pieces belonging to the Black player are marked by uppercase characters; the lower side of the chessboard belongs to him, hence black pawns move upwards. A blank line follows after every chessboard. The number or placement of the pieces may by all means be impossible to reach in a standard game of chess, however you may assume that on every chessboard there is exactly one white king (' k ') and one black king (' K ').  Output For each chessboard output one line with one of the following messages: " Safe ", if neither players' kings are being threatened " Impossible ", if both players' kings are being threatened " {colour} Check ", where {colour} is either " Black " or " White ", if the respective player's king is being threatened, and there exists at least one valid move by any of his pieces after which his king is no longer threatened " {colour} Checkmate ", where {colour} is either " Black " or " White ",  if the respective player's king is being threatened, and there exists no valid move by any of his pieces after which his king is no longer threatened Additional note There are 13 input files "0" through "12". In order to make finding mistakes easier and/or let you implement various chesspieces one by one, with the exception of the example (file #0), the following holds: Chesspiece      Appears first in file # King 1 Knight 1 Rook 3 Bishop 5 Queen 5 Pawn 8 Additionally, after submission you can view extra information about the result of each file by clicking the result text ("accepted", "wrong answer",...). As an example, if you have received WA, the extra information looks like so: File #5: Result is WA, message is 'Test Case 47: Your answer: Black Checkmate; Correct answer: Black Check', time = 0.100000, mem = 123456 Note that the message can go haywire if your program does something unexpected, such as end before reading all input.  Example Input: 7 ....k... ........ ...H.... ........ ...h.... ........ ....K... ........ ........ ....h... ..k..... .....H.. ...K.... ........ ........ ........ k..H.... ...H.... .HH..... ........ ........ ......K. ........ ........ k..H.... ...H.... .HH..... ........ ........ ......K. .r...... ........ K.....Rr R.h....r ........ ........ rr...... .....k.. ........ ........ k....... .......R ........ ...B.... .R...... ......K. ..q..... ........ ........ ..PPP... ..PkP... ...Pp... ...K.... ........ ........ ........ Output: Impossible Safe White Checkmate White Check Black Checkmate White Check Black Check This is my first time using my own judge/master judge; although this problem is 'interactive' in order to get the info message, the input is all given first before your output is read, so hopefully it should have no effect. If you have a suspicion it is doing something funky, do let me know :)
34,284
Chessboard State 2: International Chess Tournament (CSTATE2) Note: This is a harder version of CSTATE1 - a solution to this problem will (except I/O format) pass there. It is also an easier version of CSTATE3 - the solution to it will pass here. V Slovakistane sa rozhodli osadníci usporiadať národný šachový turnaj.  Za prvé miesto sa dá získať diplom, a tak všetci hrajú ako o život.  Keďže sa však nehrá na čas, vyskytol sa problém -- hráči nechceli priznať prehru. Stále len tvrdili, že určite nemajú mat, však určite sa z tej situácie dá nejak dostať, keby len mali ešte chvíľku na rozmýšlanie... A možno ešte jednu... Na budúci rok sa bude TMŠ v Slovakistane organizovať zas, ale je potrebné tento problém dovtedy nejako vyriešiť. ## Úloha Pre daný popis šachovnice rozlíšte, či má niektorý z hráčov šach alebo mat. Pritom berte do úvahy len obyčajné pohyby figúrok (komplikované ťahy ako *rošáda*, *en passant*, *pohyb pešiakom o dva políčka vpred* a *povýšenie pešiaka* sa v Slovakistane neakceptujú). ## Formát vstupu V prvom riadku je číslo $1 \leq t \leq 1000$, udávajúce počet šachovníc na vstupe. Nasleduje $t$ popisov šachovníc. Každý popis šachovnice pozostáva z ôsmich riadkov, každý obsahujúci osem znakov (teda šachovnica má klasické rozmery $8 \times 8$). Tieto znaky sú `.KQRBHP`, reprezentujúce v tomto poradí voľné políčko, kráľa, kráľovnú, vežu, strelca, koňa, a pešiaka.  Bielemu hráčovi patrí horná strana šachovnice (skôr na vstupe) a jeho figúrky sú označené malými písmenami. Teda bieli pešiaci sa pohybujú smerom dole. Čiernemu hráčovi patrí dolná strana šachovnice a jeho figúrky sú označené veľkými písmenami. Jeho pešiaci sa pohybujú smerom hore. Za každým popisom šachovnice je jeden prázdny riadok. Počet ani poloha figúrok nijak nemusia byť dosiahnuteľné v klasickej hre šachu, avšak môžete predpokladať, že na každej šachovnici sa nachádza práve jeden biely kráľ (`k`) a práve jeden čierny kráľ (`K`).  Navyše, figúrky sa vo vstupoch budú vyskytovať nasledovne: | Číslo sady | Nové figúrky | | :--------: |------------------| |  $1$ | Kráľ, kôň | |  $2$ | Veža | |  $3$ | Strelec, kráľovná| |  $4$ | Pešiak | ## Formát výstupu Pre každú šachovnicu vypíšte jeden riadok s jednou z nasledovných hlášok: +   "Neutralna situacia.", ak žiaden z kráľov nie je ohrozený nepriateľskou figúrkou. +   "Nemozna situacia.", ak sú obaja králi ohrození nepriateľskou figúrkou. +   "{farba} hrac ma sach.", kde {farba} je "Biely", resp. "Cierny", ak je kráľ tohto hráča v ohrození, ale existuje platný ťah niektorou z jeho figúrok taký, po ktorom už v ohrození nebude. +   "{farba} hrac ma mat.", kde {farba} je "Biely", resp. "Cierny", ak je kráľ tohto hráča v ohrození, a neexistuje platný ťah niektorou z jeho figúrok taký, po ktorom už v ohrození nebude.   A year ago the inhabitants of Slovakistan decided to organize a national chess tournament. Since the first place prize was 1 point on SPOJ, everyone played as if their life was at stake. However, since time was not measured in this chess tournament (unlike at most chess tournaments in the rest of the world), a problem occured - players took way too long to admit defeat. They always just kept thinking and thinking, trying to find some move which would prevent their king from being taken. Just one more moment... And perhaps one more... Luckily, a skilled programmer lent them a hand and got rid of this nuisance! This year, they are organizing a chess tournament once more. However, since word got out of how awesome it was, contestants from all over the world are planning to join. Slovakistan can not embarras itself - this year's tournament has to be more awesome, way more dramatic, and - most importantly - a whole lot bigger. Hence, during this year's tournament the contestants will not only play on the classic 8-by-8 chessboards, but rather on n-by-n boards. That gives rise to a new problem though - the programs of skilled programmers which helped them last year are not capable of deciding the state of chessboards of such size! Once again, the inhabitants of Slovakistan need your help. For a given description of a chessboard, decide its state - which player's king is under threat, and whether it is a check or a checkmate. Additionally, if it's a check, to help build up suspense, the contestants would like to know the number of valid moves the checked player has after which his king is no longer threatened. For the purposes of this problem only take into account basic moves of every chesspiece; complicated moves such as Castling, En passant, moving a pawn 2 squares or Promotion are not accepted in Slovakistan. Input The first line of the input contains the integer 1 ≤ t ≤ 12000  - the number of chessboards. t descriptions of a chessboard follow. The first line of each description contains two integers 8 ≤ n ≤ 10 5 , 2 ≤ p ≤ 10 5   - the length of side of the chessboard and the number of pieces currently on it. p lines follow, each in the form ' x y c ' , where 1 ≤ x,y ≤ n indicate the coordinates of the chesspiece; the upper-left square has coordinates (1,1) while the bottom-right square is at (n,n) . c  represents the type of the chesspiece - this character is from the set {KQRBHPkqrbhp} , representing in this order the king, queen, rook, bishop, knight (horse), and pawn. The pieces belonging to the White player are marked by lowercase characters; the upper side of the chessboard (lower y coordinates) belongs to him, hence white pawns move in the positive y  direction. The pieces belonging to the Black player are marked by uppercase characters; the lower side of the chessboard (greater y coordinates) belongs to him, hence black pawns move in the negative y direction. A blank line follows after every chessboard description. The number or placement of the pieces may by all means be impossible to reach in a game of chess, however you may assume that on every chessboard there is exactly one white king (' k ') and one black king (' K '). No two pieces are on the same coordinates. Input files are 'reasonable' - that is, if a file contains a large amount of testcases, they are reasonably small. Specifically, the sum of n+p  within an input file does not exceed 450,000 . Output For each chessboard output one line with one of the following messages: " Safe ", if neither players' kings are being threatened " Impossible ", if both players' kings are being threatened " {colour} Check - m Plausible Moves ", where {colour} is either " Black " or " White ", if the respective player's king is being threatened, and there exists m valid moves by his pieces after which his king is no longer threatened " {colour} Checkmate ", where {colour} is either " Black " or " White ",  if the respective player's king is being threatened, and there exists no valid move by any of his pieces after which his king is no longer threatened Additional note There are 16 input files "0" through "15". File 0 is the example given below. File 1 contains roughly a half of the testdata from CSTATE1; file 2 contains the rest of testdata from CSTATE1, along with some chessboards of size 100. Time limit is 2.5 seconds for each file - four times my worst time on any input file. Despite that, if you believe your solution runs just slightly longer, ping me and I might increase it. After submission you can view extra information about the result of each file by clicking the result text ("accepted","wrong answer",...), such as the result of each file and the time/memory used, but no message is present like in CSTATE1 - if you are stuck, consider submitting there for a hint at what is off in your solution. Example Input: 7 8 4 5 1 k 4 3 H 4 5 h 5 7 K 8 4 5 2 h 3 3 k 6 4 H 4 5 K 8 6 1 1 k 4 1 H 4 2 H 2 3 H 3 3 H 7 6 K 8 7 1 1 k 4 1 H 4 2 H 2 3 H 3 3 H 7 6 K 2 7 r 8 9 1 1 K 7 1 R 8 1 r 1 2 R 3 2 h 8 2 r 1 5 r 2 5 r 6 6 k 8 6 1 1 k 8 2 R 4 4 B 2 5 R 7 6 K 3 7 q 8 9 3 2 P 4 2 P 5 2 P 3 3 P 4 3 k 5 3 P 4 4 P 5 4 p 4 5 K Output: Impossible Safe White Checkmate White Check - 1 Plausible Moves Black Checkmate White Check - 1 Plausible Moves Black Check - 5 Plausible Moves If you have any questions, problems or suggestions, do let me know :)
34,285
Chessboard State 3: Intergalactic Chess Tournament (CSTATE3) Note: This is a harder version of CSTATE1 and CSTATE2 - a solution to this problem will (except I/O format) pass there. V Slovakistane sa rozhodli osadníci usporiadať národný šachový turnaj.  Za prvé miesto sa dá získať diplom, a tak všetci hrajú ako o život.  Keďže sa však nehrá na čas, vyskytol sa problém -- hráči nechceli priznať prehru. Stále len tvrdili, že určite nemajú mat, však určite sa z tej situácie dá nejak dostať, keby len mali ešte chvíľku na rozmýšlanie... A možno ešte jednu... Na budúci rok sa bude TMŠ v Slovakistane organizovať zas, ale je potrebné tento problém dovtedy nejako vyriešiť. ## Úloha Pre daný popis šachovnice rozlíšte, či má niektorý z hráčov šach alebo mat. Pritom berte do úvahy len obyčajné pohyby figúrok (komplikované ťahy ako *rošáda*, *en passant*, *pohyb pešiakom o dva políčka vpred* a *povýšenie pešiaka* sa v Slovakistane neakceptujú). ## Formát vstupu V prvom riadku je číslo $1 \leq t \leq 1000$, udávajúce počet šachovníc na vstupe. Nasleduje $t$ popisov šachovníc. Každý popis šachovnice pozostáva z ôsmich riadkov, každý obsahujúci osem znakov (teda šachovnica má klasické rozmery $8 \times 8$). Tieto znaky sú `.KQRBHP`, reprezentujúce v tomto poradí voľné políčko, kráľa, kráľovnú, vežu, strelca, koňa, a pešiaka.  Bielemu hráčovi patrí horná strana šachovnice (skôr na vstupe) a jeho figúrky sú označené malými písmenami. Teda bieli pešiaci sa pohybujú smerom dole. Čiernemu hráčovi patrí dolná strana šachovnice a jeho figúrky sú označené veľkými písmenami. Jeho pešiaci sa pohybujú smerom hore. Za každým popisom šachovnice je jeden prázdny riadok. Počet ani poloha figúrok nijak nemusia byť dosiahnuteľné v klasickej hre šachu, avšak môžete predpokladať, že na každej šachovnici sa nachádza práve jeden biely kráľ (`k`) a práve jeden čierny kráľ (`K`).  Navyše, figúrky sa vo vstupoch budú vyskytovať nasledovne: | Číslo sady | Nové figúrky | | :--------: |------------------| |  $1$ | Kráľ, kôň | |  $2$ | Veža | |  $3$ | Strelec, kráľovná| |  $4$ | Pešiak | ## Formát výstupu Pre každú šachovnicu vypíšte jeden riadok s jednou z nasledovných hlášok: +   "Neutralna situacia.", ak žiaden z kráľov nie je ohrozený nepriateľskou figúrkou. +   "Nemozna situacia.", ak sú obaja králi ohrození nepriateľskou figúrkou. +   "{farba} hrac ma sach.", kde {farba} je "Biely", resp. "Cierny", ak je kráľ tohto hráča v ohrození, ale existuje platný ťah niektorou z jeho figúrok taký, po ktorom už v ohrození nebude. +   "{farba} hrac ma mat.", kde {farba} je "Biely", resp. "Cierny", ak je kráľ tohto hráča v ohrození, a neexistuje platný ťah niektorou z jeho figúrok taký, po ktorom už v ohrození nebude.   A thousand years ago the inhabitants of Slovakistan decided to organize a national chess tournament. Since the first place prize was 1 point on SPOJ, everyone played as if their life was at stake. However, since time was not measured in this chess tournament (unlike at most chess tournaments in the rest of the world), a problem occured - players took way too long to admit defeat. They always just kept thinking and thinking, trying to find some move which would prevent their king from being taken. Just one more moment... And perhaps one more... Luckily, a skilled programmer lent them a hand and got rid of this nuisance! The next year, they organized a chess tournament once more. However, since word got out of how awesome it was, contestants from all over the world joined. Slovakistan could not embarras itself - that year's tournament had to be more awesome, way more dramatic, and - most importantly - a whole lot bigger. Hence, during that year's tournament the contestants did not only play on the classic 8-by-8 chessboards, but rather on n-by-n boards. That gave rise to a new problem though - the programs of skilled programmers which helped them the previous year were not capable of deciding the state of chessboards of such size! Once again, the inhabitants of Slovakistan needed help.  That is the origin story of the now most popular tournament in the entire universe. These days all the galactic empires have a ceasefire in the intergalactic wars to all take part in the Intergalactic Chess Tournament. For its thousandth aniversary, the Slovakistan Milky Way Empire is preparing a truly spectacular show - the chesspieces this year will be represented by planets, and the chessboard will be an entire galaxy! As in the legendary tale from a thousand years ago, they are facing the same problem: the programs written to decide the state of a chessboard can not handle the size of the chessboard, even when run on the most modern quantum computers. To tackle this problem, they have constructed a time machine to come to this legendary time - and look for a skilled programer who could help them with this task! For a given description of a chessboard, decide its state - which player's king is under threat, and whether it is a check or a checkmate. Additionally, if it's a check, to help build up suspense, the contestants would like to know the number of valid moves the checked player has after which his king is no longer threatened. For the purposes of this problem only take into account basic moves of every chesspiece; complicated moves such as Castling, En passant, moving a pawn 2 squares or Promotion are not accepted in the known universe. Input The first line of the input contains the integer 1 ≤ t ≤ 20000  - the number of chessboards. t descriptions of a chessboard follow. The first line of each description contains two integers 8 ≤ n ≤ 10 18   , 2 ≤ p ≤ 2*10 5   - the length of side of the chessboard and the number of pieces currently on it. p lines follow, each in the form ' x y c ' , where 1 ≤ x,y ≤ n indicate the coordinates of the chesspiece; the upper-left square has coordinates (1,1) while the bottom-right square is at (n,n) . c  represents the type of the chesspiece - this character is from the set {KQRBHPkqrbhp} , representing in this order the king, queen, rook, bishop, knight (horse), and pawn. The pieces belonging to the White player are marked by lowercase characters; the upper side of the chessboard (lower y coordinates) belongs to him, hence white pawns move in the positive y  direction. The pieces belonging to the Black player are marked by uppercase characters; the lower side of the chessboard (greater y coordinates) belongs to him, hence black pawns move in the negative y direction. A blank line follows after every chessboard description. The number or placement of the pieces may by all means be impossible to reach in a standard game of intergalactic chess, however you may assume that on every chessboard there is exactly one white king (' k ') and one black king (' K '). No two pieces are on the same coordinates. Input files are 'reasonable' - that is, if a file contains a large amount of testcases, they are reasonably small. Specifically, the sum of p  within an input file does not exceed 10 6 . Output For each chessboard output one line with one of the following messages: " Safe ", if neither players' kings are being threatened " Impossible ", if both players' kings are being threatened " {colour} Check - m Plausible Moves ", where {colour} is either " Black " or " White ", if the respective player's king is being threatened, and there exists m valid moves by his pieces after which his king is no longer threatened " {colour} Checkmate ", where {colour} is either " Black " or " White ",  if the respective player's king is being threatened, and there exists no valid move by any of his pieces after which his king is no longer threatened Additional note There are 16 input files "0" through "15". File 0 is the example given below. Files 1 through 7 contain testdata from CSTATE2. After submission you can view extra information about the result of each file by clicking the result text ("accepted","wrong answer",...), such as the result of each file and the time/memory used, but no message is present like in CSTATE1 - if you are stuck, consider submitting there for a hint at what is off in your solution. Example Input: 7 8 4 5 1 k 4 3 H 4 5 h 5 7 K 8 4 5 2 h 3 3 k 6 4 H 4 5 K 8 6 1 1 k 4 1 H 4 2 H 2 3 H 3 3 H 7 6 K 8 7 1 1 k 4 1 H 4 2 H 2 3 H 3 3 H 7 6 K 2 7 r 8 9 1 1 K 7 1 R 8 1 r 1 2 R 3 2 h 8 2 r 1 5 r 2 5 r 6 6 k 8 6 1 1 k 8 2 R 4 4 B 2 5 R 7 6 K 3 7 q 8 9 3 2 P 4 2 P 5 2 P 3 3 P 4 3 k 5 3 P 4 4 P 5 4 p 4 5 K Output: Impossible Safe White Checkmate White Check - 1 Plausible Moves Black Checkmate White Check - 1 Plausible Moves Black Check - 5 Plausible Moves If you have any questions, problems or suggestions, do let me know :)
34,286
Where The Friends Meet! (WTFM) As you might be knowing, Blackhood, Kira and BaZ are very good friends. They are going to meet after a long time (not that long though :p). They live in a country with N cities. Each city has a GDP (not necessarily distinct). The roads of the country are such that there is only one road connecting any two cities in the country. Kira and Blackhood decide to meet anywhere in the unique path between their cities (including their cities too). But BaZ is not ready to meet anywhere, since he likes numbers having at least K distinct prime factors, he agrees to meet only in those cities whose GDP is a number he likes. Given Blackhood's and Kira's home cities, you need to find the number of cities where they can meet. i.e. you need to tell the number of cities between Blackhood's and Kira's home city which have their GDP a number BaZ likes. Input First line of the input contains three integers N, representing the number of cities in the country, K (as explained above) and Q, the number of queries which are to be answered). (1 ≤ N, Q ≤ 200000, 0 ≤ K ≤ 100). Next line contains N integers, where the ith integer represents the GDP of the ith country (1 ≤ GDP[i] ≤ 1000000). The next N-1 lines contain two integers u and v, representing a road between city u and city v (1 ≤ u, v ≤ N). Then the Q following lines contain two integers u and v, representing Blackhood's and Kira's home cities. Output For each query, output an integer representing the number of cities where the three can meet. Note: Large input data, use FAST I/O. Be careful with certain languages too. Example Input: 5 2 5 10 1 6 9 14 1 2 2 4 1 3 3 5 1 2 4 5 2 3 2 5 3 5 Output: 1 3 2 3 2
34,287
Degree of a Tree (TREEDEGREE) mrm_196 always represents the rooted trees in a simple array, but the array holds four conditions: If the tree has N vertices, the array has length 2N. Each vertex has a number (from 1 to N) which is written twice (but they may not be necessarily beside each other). Between the numbers of each vertex, the numbers on its subtree are written. Vertex 1 is always the root of the tree. For example, he may store the following tree in one of these six ways:   Tree = {1, 3, 2, 2, 4, 4, 5, 5, 3, 1} Tree = {1, 3, 4, 4, 2, 2, 5, 5, 3, 1} Tree = {1, 3, 5, 5, 4, 4, 2, 2, 3, 1} Tree = {1, 3, 2, 2, 5, 5, 4, 4, 3, 1} Tree = {1, 3, 4, 4, 5, 5, 2, 2, 3, 1} Tree = {1, 3, 5, 5, 2, 2, 4, 4, 3, 1}   Your task is pretty simple, find what he always wanted, THE DEGREE OF THE TREE!!!! Degree of a tree is the maximum degree of all its vertices. Input The first line of the input contains an integer  T  (1 ≤  T  ≤ 20) — the number tests to answer. The first line of each test contains an integer  N  (1 ≤  N  ≤ 100 000) — the number of vertices in the tree. The second line of each test contains 2 N  integers  a 1 ,  a 2 , ...,  a 2N  (1 ≤  a i  ≤  N ) — the elements of his array. It’s guaranteed that the given array always forms at least one valid tree. Output For each test, print a single integer in one line — the degree of the tree. Example Input: 2 1 1 1 5 1 3 2 2 4 4 5 5 3 1 Output: 0 4 Warning: large Input/Output data, be careful with certain languages
34,288
Flirtatious Verma (VDATE) Harsh Verma is a college guy who likes to date a lot of girls. He has got great flirting skills and he managed to convince a lot of girls to go out with him. He knows X dating locations in his city. He wanted to date all the girls so he started assigning each of them some dating locations. He treated all girls equal so he gave each of them equal number of dating locations. He wanted to spend maximum possible time with each girl so he tried to maximise the number of dating locations given to each girl . Also, no two girls got the same dating location. After the distribution, he was left with Y dating locations. But unfortunately, he was too excited and he forgot to count the number of girls he had already assigned the dating locations . This was a difficult situation for him but Aditya (Sciencepal) came to his rescue. He gave him a list of possible number of girls to him which would help him to figure out the actual number of girls. Your task is to write a program to find the total count of possible number of girls i.e. the number of entries in the list prepared by Sciencepal. If there are infinite possibilities, print -1. If there is no solution, print 0. Input First line will contain an integer T i.e. the number of test cases. (1 ≤ T ≤ 50) Next T lines will contain two integers X and Y . (0 ≤ X ≤ 1000000000, 0 ≤ Y ≤ 1000000000) Output For each test case, print a single integer denoting the count of possible number of girls. Example Input: 1 14 2 Output: 4 Explanation If X = 14 and Y = 2 then the possible number of girls are 3, 4, 6 and 12.
34,289
SUMMATION (SUMMATION) You are given an array of integer. You have to find the sum of all possible subsequences sum of the array. For example: The given array of length n = 3 is {1, 2, 3}. All the subsequences of this array with the corresponding array summations are: Subsequence Summation {} 0 {1} 1 {2} 2 {3} 3 {1,2} 3 {1,3} 4 {2,3} 5 {1,2,3} 6 Total 24 The answer is 24. Input The first line of input will contain the test case T (1 <= T <= 10) . There will be two lines for each test case. First line will contain the value of n (1 <= n <= 1000) and the next line will contain the array elements space-separated integers. Each integer will be between 1 and 1000000000. Output For each case of input, output the answer of the problem in the format " Case X: Y " where X denotes the number of the test case and Y denotes the answer. Answer could be very large so output the answer modulo 100000007 . Example Input: 2 3 1 2 3 3 4 1 2 Output: Case 1: 24 Case 2: 28
34,290
Ada and Cherry (ADACHERY) As you might already know, Ada the Ladybug is a farmer. She grows cherry and now she wants to collect them. She is wondering about the number of cherries she will collect. But before you could help here, you shall know some biological facts: Firstly, almost everyone think that cherry-tree is a tree. But it might not be true - in fact, it is a graph. Secondly, you have to know, how a cherry looks like. It is not hard to recognize a cherry - it is a node, which is connected to another two nodes, which are NOT connected. NOTE : Even though the cherry-tree structure might be weird, note that there won't be any multi-branches nor self-branches. Anyway do not assume it is not a cherry-forest. This is a cherry: This is NOT a cherry:   Input The first line contains two integers 1 ≤ N, M ≤ 10 5 , the number of nodes of cherry-tree and the number of branches (edges) connecting them. The next M lines contains two integers 0 ≤ a, b < N , the branch connecting two nodes. Output Print a single line - the number of cherries on the cherry-tree. Example Input 4 2 1 2 3 2 Example Output 1 Example Input 2 5 4 1 2 1 3 1 4 1 0 Example Output 2 6 Example Input 3 6 6 0 1 0 2 2 1 0 3 1 4 5 3 Example Output 3 5
34,291
Right Shift (RSHIFT) All the numbers in a computer is represented as 64-bit 2's complement form. You have to write a program to perform the following task :- Read the number (given in decimal form). Shift all the bits towards right (the first bit is removed), i.e the second bit from right is shifted to first position, third to second and so on. Add a zero to the last position. Write the result back in decimal form   For example 10 is represented as: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1010 After step 2 the result is: _000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0101 After step 3 the result is: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0101 Finally the output is: 5 Input The first line contains T representing the number of test cases (T<=500000). Then T lines follows each containing a input number. Output Print T lines, each containing the result of each test case. Constraints All input and output numbers will fit in signed 64-bit integer. Large I/O. A fast code written in fast language is likely to pass. Example Input: 5 1 2 3 4 5 Output: 0 1 1 2 2
34,292
Share It (SHAREIT) There are some friends living in a hostel who share many things among them daily. They are very economical and never want to waste a penny. Whenever they need something which they can share among them to save money, they do. But the real problem is: whenever they buy some item which they'll share among them, it's very difficult to share the price of the item among them instantly e.g. some item costs 10 bucks and to be shared among 3 friends, each friend gets a share of 3.33 bucks to pay, it's difficult to share it instantly, isn't it? I mean all of them may not have exactly 3.33 bucks in their wallet to pay for settlement. Assume they always pay in cash and share the price of the item equally among them. So, all the friends come up with below idea to ease their lives: "Every time we buy some item which is going to be shared among some or all of us, we need not share its price while buying it. Instead one or some of us will pay it while buying and record it for settlement at the end of month." Basically, they need a software application where "they can record the purchase of a shared item with its name, purchase date, price, who paid how much while buying it and among whom the item is going to be shared. At the end of the month, the application should be able to find out, who owes how much to whom." So far, so good. But... At the end of the month, the application should find out the minimum number of transactions needed among friends for settlement. Say, A needs to pay 10 bucks to B (A→B: 10) and B needs to pay 5 bucks to A (B→A: 5), then A can just pay 5 bucks to B (A→B: 5) and so only 1 transaction is enough for settlement. Similarly, if A→B: 10 and B→C: 10, then A→C: 10 (only 1 transaction is enough again). Sum of the amounts in all transactions in final settlement should be minimum. Say, A→B: 10 and B→C: 5 (sum of the amounts = 10+5 = 15), then A→B: 5 and A→C: 5 (sum of the amounts = 5+5 = 10) should be the transactions in final settlement. Input First line of input will contain the number of test cases T (1 <= T <= 100) . T test cases follow. First line of each test case will contain two integers N and S , the number of friends N (1 <= N <= 100) numbered from 1 to N and the number of transactions S (1 <= S <= 1000) amongst friends within a month. 2 nd to (S+1) th lines of each test case will contain the descriptions of all S transactions, one transaction per line in this format (all values are space separated, angular brackets are for clarification only): <F> <A> <B 1 > <B 2 > ... <B N > where F (1 <= F <= N): serial number of a friend, A (0.01 <= A <= 10000.00): amount with 2 decimal places paid by F in this transaction and  B i (0 or 1):  0 if the amount A is not to be shared with friend numbered i , 1 if it is to be shared with friend numbered i . Amount is shared with at least one of the friends. (Note: if amount A is to be shared among n friends, truncate each share i.e. A/n  to 2 decimal places. e.g. if A=10.00 and n=3, then A/n=3.33, similarly if A=20.00 and n=3, then A/n=6.66) Output For each test case, find a solution with minimum number of transactions in final settlement, with sum of the amounts involved in those transactions being minimum (call it MINIMUM_SUM_AMOUNTS ). Output a single line for each test case containing the MINIMUM_SUM_AMOUNTS with 2 decimal places only. Example Input: 2 2 2 1 5.00 0 1 2 10.00 1 0 3 2 2 10.00 1 0 0 3 5.00 0 1 0 Output: 5.00 10.00 Explanation: 1. For 1st testcase, friend #1 will pay 5.00 bucks to friend #2 in the final settlement. (MINIMUM_SUM_AMOUNTS = 5.00) 2. For 2nd testcase, friend #1 will pay 5.00 bucks each to friend #2 and friend #3 in the final settlement. (MINIMUM_SUM_AMOUNTS = 5.00 + 5.00 = 10.00)
34,293
Ada and Panels (ADAPANEL) Ada the Ladybug has proved successful in solving some hard problems, so a construction company has asked her to solve a problem for them. There are multiple cities in the country and each city owns exactly one panel-block. There are also unidirectional roads between some pairs of cities (note that circular self-roads and multi-roads with several traffic lines are allowed). A city can sell its panel-block to any city, to which they could transport the panel block, and from which they can bring back their reward for it (i.e. there must be a path from actual city to destination city and back). As long a city has K panel-blocks, it builds a prefab of height K which looks exactly same as each other prefab of height K . The construction company notes all the heights down and puts them in an array. They are wondering how many distinct arrays are possible by moving the panel blocks between cities. However there is a catch. Consider a set of cities in which each city is reachable by every other city. Since we can easily shuffle the panel blocks between such a set of cities, we can create new permutations with the same set of heights. The construction company will NOT count any such cases. Hence they will only consider the distinct set of heights for such a set of cities. You have proved successful in helping Ada with some hard problems, so she has asked you to help her. Your job is following - count the number of possible structures which could arise. Since this number might be pretty big, you have to output it modulo 10 9 +7 . Input The first line contains two integers 1 ≤ N, M ≤ 2*10 5 , the number of cities an the number of unidireectional roads between them. The next M lines contains two integers 0 ≤ a, b < N , the road from city a to city b Output Print a single line - the number of possible structures modulo 1000000007 . Example Input 7 9 0 1 1 2 2 3 3 1 2 0 4 5 5 4 6 4 5 6 Example Output 15 Example Input 2 7 7 0 1 1 2 2 3 3 4 4 5 5 6 6 0 Example Output 2 15 Example Input 3 6 3 0 1 3 2 4 5 Example Output 3 1 Example Input 4 8 7 0 1 1 0 2 3 3 2 4 5 5 6 6 4 Example Output 4 12
34,294
Ada and Lychees (ADALICI) As you might already know, Ada the Ladybug is a farmer. She grows lychee tree. Unlike a cherry tree, lychee tree really forms a tree (obviously a rooted tree - in node 0 ). The lychee fruits grow in bunches (there are (usually) multiple lychee fruits in each node). Ada will give you many queries, for harvesting lychees, consisting of 3 numbers: index of node U , I th ancestor , L new lychees , meaning, that she wants to harvest lychees of I th ancestor of node U . Afterward L new lychee fruits will grow on the node. She wants you to sum all those harvest-values and output the sum. Value of harvest can be counted as X*W , where X is number of node where you'll harvest and W is the number of lychees in it. Also note that input's format won't be easy (as usual). You will be given description of the tree and x 0 , a, b . The next term could be counted as x i =(a*x i-1 +b)%MOD , where % means modulo and MOD is equal to 10^9+7 ( 1000000007 ) Firstly, you can set the number of lychees on each node: The number of lychee fruits on node i is equal to x i %100003 ( 10 5 +3 ). Afterward there will be Q queries, giving you U, I, L (denoting XT as next x i ), U=XT%N , I=XT%(D[U]+1) (where D indicates DEPTH - root has depth 0), L=XT%100003 [priority of XT is from left to right]. NOTE: Parent of every node will always have lesser ID than the node itself (since the lychees far away from root are much more juicy). Input The first line contains five integers N, Q, x i , a, b: 1 ≤ N ≤ 2*10 5 , 1 ≤ Q ≤ 4*10 7 , 0 ≤ a, b, x 0 < 1000000007 The next N-1 lines contains two integers 0 ≤ a < b < N , the branch connecting two nodes. Output Print a single line - the number sum of values over all queries. Example Input 5 3 1 1 1 0 1 1 2 0 3 2 4 Example Output 13 Additional Information #LYCHEES: 1 2 3 4 5 QUERY 1: 1 1 8 QUERY 2: 4 2 11 QUERY 3: 2 1 14 Example Input 2 5 5 2 3 4 0 1 1 2 2 3 2 4 Example Output 2 113299 Additional Information 2 #LYCHEES: 2 10 34 106 322 QUERY 1: 0 0 8746 QUERY 2: 2 1 36188 QUERY 3: 1 0 77101 QUERY 4: 4 2 81719 QUERY 5: 0 0 26368 Example Input 3 10 100 666 561 14159 0 1 0 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 Example Output 3 9060951 Example Input 4 20 10000 30355495 415740782 580959825 0 1 1 2 2 3 3 4 3 5 0 6 6 7 7 8 8 9 3 10 1 11 3 12 11 13 3 14 3 15 4 16 16 17 8 18 17 19 Example Output 4 1939449924
34,295
SOLVEIT (SOLVEIT) Problem setter of INSOMNIA, MNNIT Allahabad decided to set a easy problem for all coders so that they can easily solve the problem and boost their confidence for rest of INSOMNIA. The problem is a follows: You are given an array of size n which is initialized with 0. You will be given q queries of two types: Type 1: set in (input value) index k to -1. Type 2: print the index which has value -1 and is greater or equal to input index y. If there is no such value print -1. Note: Indexing is 1 based. Input First line contains two integers n and q separated by spaces. Next q lines contains type of query and for type 1 query integer k separated by a space and for type 2 integer y separated by a space. 1 <= n <= 10^6 1 <= q <= 10^6 1 <= y, k <= n Output Print a single line for each query type 2 containing index which has value -1 and is greater or equal to input index y. Example Input: 5 5 2 3 1 2 2 1 2 3 2 2 Output: -1 2 -1 2
34,296
Apoorv and Maximum Inversion (SAS001) Apoorv has an array of n integers. Inversion count of an array is defined by number of pair of indices(i,j) such that i arr[j]. You are given an integer p. Apoorv has to find the subarray with maximum inversion count among all subarrays of size p. Apoorv find this job very tough so he turns to you for help. Constraints : 1<=n<=500000 -1000000000<=arr[i]<=1000000000 1<=p<=n Input First line contains two integers n and p. Next line contains n space separated integers denoting the elements of the array. Output Output two space separated integers first integer should be the starting index (1-based indexing) of the subarray and next integer would be the count of inversions in that subarray .In case there is a tie in maximum inversion count  print the smallest starting index among the subarrays having maximum inversion count. Example Input: 10 5 15 51 44 44 76 50 29 88 48 50 Output: 5 6
34,297
Apoorv and Math problem (SAS002) Apoorv is an expert in maths .There are very few questions in maths that Apoorv is unable to answer. Apoorv's teacher is not very fond of Apoorv. So he decided to give Apoorv a  function value to calculate. Apoorv is unable to solve this problem and turns to you for help. Help him to find the answer to the function quickly. Apoorv's teacher will only check the final answer. So Apoorv is free to do calculate the value by any function he likes but the final answer should be same. Also as his teacher don't like him much he gave him a very strict time limit to solve the problem. Help Apoorv in finding the answer quickly. The function given by Apoorv's teacher is as follows: function ( number ) { answer = 1 for ( each i from 1 to number ) { if ( number modulo i is 0 ) { answer=answer multiplied by i   } } return answer } Constraints At max 100 numbers will be given by Apoorv's teacher. The value of number given by Apoorv's teacher will easily fit into 64 bit-integer and will always be positive. Input First line will contain t denoting t numbers that are given by Apoorv's teacher. Next t lines will contain a single integer denoting the number. Output For each t numbers output the value of answer in new line. Since the value of answer can be very large Apoorv's teacher is fine with you reporting the answer modulo 10 9 +7. Example Input: 2 1 2 Output: 1 2
34,298
Walk home together (WHT) A group of f friends get together to have a coding problem-solving party at their university computer lab every weekend. Unfortunately, it closes at 22:00, at which point they have no other option but to walk home. The city they live in can be described as n junctions connected by m bidirectional roads. Since these friends have been interrupted from coding their solutions, each one of them wants to get home as fast as possible to finish his and submit it. At the same time, they each have a few problems that they want to discuss with the others, so they will pick such a path that the entire group can walk together for as long as possible. On top of that, so that this walk would feel fresh every time, they would like to take a different path each weekend, for as long as possible. The group of friends were able to figure out both the length of the longest path they could all efficiently walk together, as well as how many distinct such paths there are - do you think you can do it too? Input The first line contains an integer T - the number of test cases. T test cases follow, each in the given format. Test cases are separated by a blank line. The first line of a case contains four integers n m c f - the number of junctions, the number of two-way roads connecting the junctions, the junction at which the c omputer lab is located, and the number of f riends. Junctions are numbered from 1 to n . The second line contains f distinct integers F 1 ... F f - F i is the junction where friend number i lives. None of them are equal to c . The following m lines contain three integers x y z , denoting a two-way road connecting junctions x and y , of length z. Each unordered pair x, y will be present at most once. You can assume that the city is connected. Output Output two integers L and W . A 'path' is a sequence of junctions a 1 ... a k where for all 1 ≤ i < k the junctions a i and a i+1 are connected by a road. L is the length of the longest path, such that for all 1 ≤ i ≤ f if after walking this path friend number i can get home the soonest at some time L + t i , there exists no path from c to F i shorter than L + t i . In other words, none of the friends could have gotten home sooner if they would have chosen a different path which did not include the one of length L . W is the number of such paths, modulo 10 9 +7 . Two paths are considered distinct if either: a) they contain a different number of junctions, or b) they contain the same number of junctions (lets call that k ), where one path is described by a 1 ... a k and the other by b 1 ... b k , and there exists some 1 ≤ i ≤ k such that a i ≠ b i . Constraints 1 ≤ f < n ≤ 5000 n-1 ≤ m ≤ min(10 6 , n × (n - 1) / 2) 1 ≤ c ≤ n 1 ≤ F i ≤ n 1 ≤ x < y ≤ n 1 ≤ z ≤ 4 × 10 5 1 ≤ T ≤ 500 Additionally, if T > 1, n ≤ 50. The largest input file is under 16MB. Example Input: 3 9 12 2 3 9 8 1 2 5 3 2 3 7 2 4 5 3 6 4 6 7 2 5 7 20 4 7 8 4 8 50 7 9 10 7 8 30 1 8 15 1 9 15 9 12 2 3 9 8 1 2 5 3 2 3 7 2 4 5 3 6 4 6 7 2 5 7 20 4 7 8 4 8 10 7 9 10 7 8 30 1 8 15 1 9 15 9 12 2 3 9 8 1 2 5 3 2 3 7 2 4 5 3 6 4 6 7 2 5 7 20 4 7 8 4 8 10 7 9 10 7 8 30 1 8 4 1 9 4 Output: 13 2 5 1 15 1 Explanation In the first case, the paths are 2, 3, 6, 7 and 2, 4, 7. Friends number 1 and 2 can then go straight home, and friend number 3 can go home either through junction 8 or 9. For each friend, this is an optimal path. In the second case, friend number 1 can get home the fastest the same ways as before, friend number 2 can get home fastest by going 2, 4, 8 and friend number 3 by going 2, 4, 8, 1. Hence the longest path which all friends are willing to take is 2, 4 of length 5, and no other such path exists. In the third case, the first friend can get home the fastest by 2, 3, 6, 7, 9 or 2, 4, 7, 9 or 2, 4, 8, 1, 9; the second friend's only fastest path is 2, 4, 8, and the third friend is only willing to take the path 2, 4, 8, 1. Hence the longest path they are all willing to take has length 15 and it is 2, 4, 8.
34,299