task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
KNIGHTS level testing (KNIGHTSG) The image above is an example of a level in Arzola's videogame 'KNIGHTS'. The rules are very simple. The player is given a chess board, where each square is either empty, contains a wall, or contains a knight of one of three colours. Some squares are also marked with a colour - the player beats the level if all marked squares contain a knight of their respective colour at the same time. To accomplish this, the player can select any knight and place him on an empty square using the classic chess knight move (2 squares in one direction, 1 square in a direction perpendicular to the first). You will help test a few new level designs for this game. Given a starting configuration and several goal configurations (depicting which squares contain which knight), find the minimum number of moves required to get to those goal configurations. Input The first line contains two integers 1 ≤ r,c < 24 . The following r lines contain c  characters each, describing the starting configuration of the level. The characters in the grid will be ' #'  for wall, ' .' for an empty square, and 'R', 'B' and 'Y' for a red, blue and yellow knight, respectively. The number of squares that are not walls will be at most 12. A blank line follows, followed by a line with an integer 1 ≤ q ≤ 75,000  - the number of suggested goal configurations for this level. You may assume that q*r*c ≤ 10 6 . q descriptions of goal configurations follow, separated by blank lines. Each description will be r  rows consisting of c characters, from the same set as the starting configuration. You may assume that the walls are at the same places as in the starting configuration, and that the number of knights of each colour is the same as the number of knights of that colour in the starting configuration. Output For each suggested goal configuration, if it is not reachable from the starting configuration in any number of moves, output -1. Otherwise, output the minimum number of moves required to reach that goal configuration from the starting configuration. Example Input: 3 4 #BYY ..R# .BYR 4 #BYY ..R# .BYR #.YY ..R# BBYR #Y.Y B.R# .YRB #..R YYB# YBR. Output: 0 1 19 -1
34,300
Ada and Replant (ADAGROW) As you might already know, Ada the Ladybug is a farmer. She grows vegetables. At the moment, all her vegetables are in one furrow. She is going to replant them into a few new furrows (while keeping the order of the vegetables). The total cost of growing the vegetables will be equal to the sum of absolute differences between neighboring vegetables. Ada wants to minimize the cost, can you help her? Input The first line of input contain 1 ≤ T ≤ 500 test-cases. The first line of each test-case contains two integers N, K 1 ≤ N ≤ 2000, 1 ≤ K ≤ 20 The next line contains N integers 0 ≤ A i < 10 4 , the costs of vegetables. NOTE: The number of test-cases varies depending on size of array (the longest array won't be a single file more than once). Output For each test-cases, print the minimal costs. Example Input 5 4 2 1 2 5 6 5 1 1 2 5 7 11 6 3 1 3 1 3 1 3 8 2 1 6 2 5 1 6 2 5 5 3 1 9 15 4 11 Example Output 2 10 0 6 5 Additional Information TEST-CASE-1: 1 2 5 6 TEST-CASE-2: 1 2 5 7 11 TEST-CASE-3: 1 1 1 3 3 3 TEST-CASE-4: 1 2 1 2 6 5 6 5 TEST-CASE-5: 1 4 9 11 15 Example Input 2 1 7 2 2 5 7 4 8 8 4 Example Output 2 5 Example Input 3 1 10 2 4 5 4 3 4 3 2 3 2 3 Example Output 3 4
34,301
Ada and Bloom (ADABLOOM) As you might already know, Ada the Ladybug is a farmer. She grows many beautiful flowers. Each of the flowers has something called "blooming value". As long as A i < A i ⊕ A j < A j (where ⊕ stands for binary XOR, and A stands for "blooming value") is true for any pair of flowers (in any order), then those flowers-pair might bloom into a wonderful blossom, if they are replanted into same box (at most 2 flowers can be put into one box). Ada wants to maximize the number of blossoms - can you find it? Input The first line of input contains 1 ≤ T ≤ 500 test-cases. The first line of each test-case contains N 1 ≤ N ≤ 5000 The next line contains N integers 0 < A i ≤ 10 18 , the blooming value of flower. NOTE: The number of test-cases varies depending on size of array (the longest array won't be a single file more than once). Output For each test-cases, print the maximal number of blossoms Ada can achieve. Example Input 1 6 7 8 5 4 8 4 9 11 6 9 9 12 12 4 6 3 7 7 4 4 10 6 9 1 8 11 4 12 3 1 2 1 10 4 12 2 5 2 Example Output 1 0 2 0 1 4 1 All possible pairs 1 Test-case 1: Test-case 2: 4 < 8 < 12 4 < 8 < 12 6 < 10 < 12 6 < 10 < 12 Test-case 3: Test-case 4: 1 < 8 < 9 Test-case 5: 1 < 2 < 3 1 < 10 < 11 1 < 2 < 3 1 < 10 < 11 2 < 8 < 10 2 < 9 < 11 3 < 9 < 10 3 < 8 < 11 4 < 8 < 12 Test-case 6: 5 < 9 < 12 Example Input 2 1 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Example Output 3 7
34,302
Sanvi and Magical Numbers (SANVI) Let us define a  Magical number  as a positive integer number which meets the following criteria on its representation: It does not contain any zeros. Each digits may appears at most twice in it. The absolute differences between summation of count of non-prime digits and count of prime-digits do not exceed K. Sanvi likes numbers which are not prime. So,  she wants to allow at most M non-prime numbers to violate the rule number-2 . Sanvi also uses following algorithm in rule number-3 to calculate count of each digit  d  in a number: count(d) = min(total occurrences of d in number, 2) You are given an integer number  N . Your task is to find the total Magical numbers in the range from  1  to  N following Sanvi's command. Since the answer could be very large, print it modulo 10^9+7 . Input Input contains several test cases up to  EOF  (End Of File), which contains three space separated integers  N (1 ≤ N ≤ 10^18), K (0 ≤ K ≤ 18) and M (0 ≤ M ≤ 5)  as described in the problem statement. Total test cases will not exceed  5 . Output Output a single integer denoting the total Magical numbers from  1 to N following Sanvi's command . Since the answer could be very large print it modulo  10^9+7 . Example Input: 10 1 0 5 3 2 Output: 9 5
34,303
Frog Party (FROGPARTY) In the local pond there are n lillypads arranged in a row - frog households - numbered 1 to n from left to right. One frog lives on each lillypad. In the afternoon, each frog returns to its household for a short nap. After they wake up from their naps, it is already evening. And what do frogs do on evenings? They throw a party! Luckily, a frog party doesn't require any special preparations - all the frogs simply meet up at a single lillypad, and the fun may begin. When a frog goes to a party, it definitely doesn't want to arrive wet. Hence, frogs may only travel to the party by jumping across lillypads. A single frog by itself can jump to a neighbouring lillypad. However, when a frog jumps to a lillypad with another frog on it, they team up - the frog that arrived jumps on the other's back, and with combined efforts (and slightly defying the laws of physics) they can jump to a lillypad which is at a distance of 2 . In general, if there are y frogs on the lillypad numbered x , they can jump to lillypads with numbers x-y and x+y (jumping outside the n lillypads is obviously forbidden - the frogs would jump into the water and get wet). When frogs from one lillypad jump onto another, they climb on the backs of the frogs which were already present, in the same order as before. On top of that, polite frog manners say that frogs should not jump on a lillypad on which there are currently no frogs. The whole process might look like this As you can imagine, when several frogs stand on another's back, it can be quite tiring. Frog Michal obviously doesn't want to do activities which are tiring. That's why he would like to propose a sequence of jumps at the next frog meeting, such that in the evening all frogs will end up meeting on one lillypad, and at the same time no frog ever climbed on Michal's back (that basically means that no frog can ever jump to the lillypad on which Michal is currently situated). Help him! Given the number of lillypads n and the number of lillypad on which Michal lives, produce a sequence of jumps so that all frogs end up on a single lillypad, and no frog ever jumps on a lillypad which currently has no frogs on it, or has frog Michal on it. Input The first line contains an integer 1 ≤  T ≤ 60 : the number of testcases. For each testcase, in the only line of input there are two whole numbers n and m ,  1 ≤ m ≤ n ≤ 10 6 : the number of lillypads (and frogs), and the number of the lillypad on which Michal lives. The sum of n  within a single input file does not exceed 2*10 6 . Output For each testcase, if no valid sequence of jumps which fulfills the criteria described exists, output "NO". Otherwise in the first line output "YES", and then describe a valid sequence of jumps. Each jump can be described by two numbers 1 ≤ a, b ≤ n , meaning that the frogs currently on lillypad a should jump to the lillypad b . Any valid sequence of jumps leading to a frog party will be accepted. The output is very large. Please be wary of your I/O speed. Example Input: 2 5 4 9 3 Output: YES 2 3 3 5 4 5 5 1 YES 1 2 3 2 4 5 6 5 7 8 9 8 8 5 2 5 The first case is depicted in the images in the problem text.
34,304
Minions v/s Minions (MINVSMIN) The minions have been recently troubling Gru for buying them bananas. Gru sets up an N×N banana field, where the cells that contain bananas are denoted by b , the cells which contains bombs are denoted by B . Two pack of minions are allowed to enter the field at a time from entry points marked in the fields as X and Y . We all know how childish they are and competitive they can be. Each pack from a position can divide themselves into four directions – up, down, left, right (they don’t cross the boundaries of the field.) They are smart enough to avoid the bombs. Whichever minion pack reaches a cell first gets to keep the banana, but if both packs reach a cell at the same time they smash the banana and do not allow each other to move ahead from that point. However, if member of the same pack meet at a cell they reunite and move ahead on their hunt for bananas. Remember though Gru has strictly asked them not to travel through already visited cells because of the dropped off banana peels (they can be messy at times too!) Gru has to figure out which pack acquired more bananas. Gru dozes off in the middle of the banana battle. Please help him to declare the winner – Pack 1 or Pack 2. PS: You can assume each pack contains infinite number of minions, so the pack never runs out of individuals while dividing themselves in the four directions. Input The first line contains number of test cases T . Following test case description contains N and N*N banana field’s description. 1 ≤ T ≤ 30 1 ≤ N ≤ 1000 Output You need to print “ Pack 1 ” if Pack 1 wins and “ Pack 2 ” if Pack 2 wins and “ Gru gets to keep all bananas! ” if there is a draw. Example Input: 2 3 bXb bBb YBb 5 BBBBB XbbbY BBBBB Bbbbb bbbbb Output: Pack 1 Gru gets to keep all bananas!
34,305
Nearest Neighbor Search (NNS) You are given N (N ≤ 100 000) d-dimensional (1 ≤ d ≤ 5) points, each having integer coordinates (X1, X2 ... Xd). Then Q (Q ≤ 100 000) queries follow. For each query you are given a d-dimensional point (not necessarily from the given N) and you are to find the squared Euclidean distance to the closest point from the given N. The coordinates of all N+Q points are generated randomly between -1 000 000 000 and 1 000 000 000. The squared Euclidean distance between two points A and B is the sum of (A.Xi - B.Xi) × (A.Xi - B.Xi) for i=1, 2 ... d. Input The first line contains three numbers - N, d and Q. The next N lines contain d integers each - the coordinates of a point. The next Q lines contain d integers each - the coordinates of a query point. Output Print the answer for each of the Q queries on separate lines. Example Input: 2 2 2 1 1 2 2 1 1 3 3 Output: 0 2
34,306
First to meet the spaceship (MEETSHIP) A spaceship has been sighted heading towards Earth. For the entire time that humanity has been monitoring it, it has not altered its course, it only changed speed for unknown reasons. As such, all the possible places on Earth where the spaceship might end up landing form a straight line; depending on how much it changes speed, it will land at different times, meaning a different point on this line due to Earth's rotation. n  people want to be the first to meet the aliens - they picked a point x i   on this line and wait at that point in their vehicle with speed v i . Now they are all anxiously waiting for the spaceship's arrival. NASA has given a list of  q most likely locations where the spaceship might end up landing - and everyone wants to know who would get to be the first to meet the aliens if the spaceship landed at each of the given points. They turned to you for help! Input The first line contains two integers 1 ≤ n , q ≤ 300,000 - the number of people wishing to meet the aliens and the number of possible points where the spaceship might land. The following n  lines contain two integers 0 ≤ x i  < 10 9   and 0 < v i ≤ 10 9   - the point on the line where the i -th person is waiting and the speed of his vehicle. Additionally, x i   = x j → v i ≠ v j . The last line contains q  distinct integers 0 ≤ q i < 10 9  - the points on the line where the spaceship might end up landing. You may assume the spaceship will not land at any point containing a person waiting in a vehicle. Output For each query q i  output the number of people who will arrive at the spaceship first if it lands at that point. A person at x j with speed v j will arrive at q i   in time | x j - q i | / v j . The people who will arrive at the spaceship first are those j  for whom the fraction is minimal out of all people. Then, in the same line, output the 1-based indices of these people as they were given in the input, sorted in ascending order. Example Input: 4 7 10 5 30 1 20 4 100 1 5 31 22 15 85 60 61 Output: 1 1 1 2 1 3 1 1 2 1 4 2 1 3 1 1
34,307
Ada and Terramorphing (ADAPHOTO) Ada the Ladybug was already on two trips this year. She visited two countries: Republic of Bugongo and Democratic Republic of Bugongo. Even though those countries are completely different and far far away from each other, Ada found some similarities. Now she is looking at photos from each of those countries and examines similarities. Sadly, both of the sequences of photos are very long so she can't handle it herself. The sequence of photos is sequence of following terrestrial formations: A hill (^), a valley (v), a plain (-), a lake ~ Find the longest common contiguous subsequence between the two sequences of photos. Important note: Terramorphism is very difficult process. One can't easily influence it so each of the terrestrial formation is generated with more or less 25%. Input The first two and the only lines of input contiguous first and second sequence of photos 1 ≤ |s 1 |, |s 2 | ≤ 10 6 Output For each test-cases, print the longest common sequence. Example Input -~^v- ^--v Example Output 1 Example Input 2 -~ -~v^^^^^v- Example Output 2 2 Example Input 3 ~-~-v--~^ ~^--^~-v Example Output 3 3 Example Input 4 ^^^v-v^^v-v-v~v- vv^v-^~~^v^~^vv~^^- Example Output 4 3 Example Input 5 ~~~vv~-~~vv~v-v--~-^-~^~-^^ ~^~--v~- Example Output 5 4
34,308
Meh and Mini Splendor (SPLEND1) Have you ever played a board-game called Splendor before? Splendor is one of many competitive board-games whose win condition is by gaining as many VP(Victory Points) as much as possible. For those who are curious about  this game, this link can be visited for the review of the game: Splendor . For a quick review about the game, in a turn, 1 player must choose 1 (one) out of 3 (three) moves provided. First, if a player predicts such card can be useful for the further turn, these cards can also be reserved using 1 (one) mileage point. (These mileage points are all limited to 10 mileage points only for one of a kind.) Second, if a player wants to invest jeweleries, players can obtain any jeweleries from the jewel shop. However, the rule of obtaining jeweleries is rather unique. A player can take 3 (three) different jeweleries at instant, or if the jewel shop has 4 or more one of a kind jewel, a player can take 2 (two) one of a kind jewel at instant. (These jewels are all limited to 10 jewels only for one of a kind.) Third, if a player has already had an adequate amount of jeweleries, player can buy cards from the bank. Victory Points can be obtained from certain cards which hold Victory Points. These cards must be bought using adequate number of jeweleries (rubies, sapphires, emeralds, diamonds, and cobalts). In order to win the game, a certain number of VP (Victory Points) are needed. One day, Waca, Yoota, Bram and I play that game (Splendor) at a certain board game store in Surabaya. However, because Waca always wins the game, we decided to change the rule of the game in order for Waca not to win most of the game. Before the game starts, we form a group of two. Waca and I are on one group, and so does Bram and Yoota. The rule of the game is only using the first and the second rule of Splendor. We do not use cards and Victory Points in order to win the game, but instead, the losing condition of the game is occurred when a player cannot make a valid move. If a player cannot make a valid move, that player and his/her teammate also lose the game. The first player to make a move is Waca; the second player to make a move is Bram; the third player to make a move is me; the fourth player to make a move is Yoota. If a player decided to take a mileage stone or the jeweleries, it is guaranteed that after a player takes such objects, there are no returns. Input The first line of input will be the integers of test cases T (T ≤ 1000) The other T line will consists five integers. These integers will consecutively represents the number of rubies, the number of sapphires, the number of emeralds, the number of diamonds, and the number of mileage points. EDIT: These five integers are all the number of jeweleries currently provided in the jeweleries shop. Output For each round, provide "Round n: " denoting the round number followed by the winner of the game. If Yoota and Bram win the game, print "Yoota & Bram win the game", else print "Meh & Waca win the game". Example Input: 5 4 1 7 2 10 0 10 2 2 4 5 5 4 4 6 1 3 10 3 2 5 2 10 0 7 Output: Round 1: Yoota & Bram win the game Round 2: Meh & Waca win the game Round 3: Yoota & Bram win the game Round 4: Meh & Waca win the game Round 5: Meh & Waca win the game
34,309
Ada and Expenses (ADASUM) Ada the Ladybug has just returned from her trips. She noted all her expenses. Sadly, she only had a small piece of paper so she had to keep it in a compressed form. The compressed form is just a very long number. To restore the expenses, simply sum all contiguous subsequences of the number. Since this number might be pretty big, you only have to output it modulo 10 9 +7 (1000000007). Can you help her to restore the number? Input The first and the only line of input contains the compressed sequence of digits ( [0..9] ): 1 ≤ |s| ≤ 2*10 6 Output Print the sum of all contiguous subsequences Example Input 123 Example Output 164 Example Input 2 001 Example Output 2 3 Example Input 3 105004400 Example Output 3 127807548 Example Input 4 4774 Example Output 4 6245 Example Input 5 4369383968 Example Output 5 353343059 Example Input 6 447723168365033648256648424988 Example Output 6 42233771
34,310
Ada and Servers (ADABASH) Ada the Ladybug has just bought a few servers. She is not a programming bug so she needs a server administrator to set everything for her. Yay, she have chosen you to help her. Your first job is simple - the servers are (somehow) connected with wires and you have to find out the number of components they form. Easy isn't it? Well sadly the servers are raw and nothing is (can be) installed on them (at the moment), so you can only use bash . Input The first line of input contains 1 ≤ N ≤ 600, 0 ≤ M ≤ 600 , the number of servers and the number of wires between them. The next M lines contains two integers 0 ≤ a, b < N , the servers which are connected by wires. Output Print the number of connected components. Example Input 6 3 1 2 3 4 5 0 Example Output 3 Example Input 2 11 9 0 10 1 6 1 8 2 7 2 8 3 4 3 6 4 7 4 10 Example Output 2 3 Example Input 3 5 2 0 4 1 4 Example Output 3 3 Example Input 4 5 1 1 2 Example Output 4 4 Example Input 5 4 2 1 3 0 2 Example Output 5 2
34,311
Ada and Roads (ADAROADS) As you might already know, Ada the Ladybug is a farmer. She grows many fruits and vegetables. She has to take care of them so she builds many roads between them. She also doesn't want to keep unnecessary roads so after building a road she cleans the rest of roads so her road-system doesn't contain any needless cycles. Each road has some maintenance cost and she always keeps roads in such ways that the total cost is minimized. Input The first line of input contains 1 ≤ N ≤ 2*10 5 , 0 ≤ M ≤ 5*10 5 , the number of vegetables and the number of roads built by Ada. The next M lines contains three integers a, b, c: 0 ≤ a, b < N, 0 ≤ c ≤ 10 9 , a ≠ b , the vegetables connected by road and its maintenance cost. To simulate the "real-time", a, b, c will be on input as a ⊕ l, b ⊕ l, c ⊕ l , where l is the last answer (start as 0) and operation stands for binary XOR. Output For each new road print the number actual best sum of maintenance costs. Example Input 5 5 4 3 6 6 7 4 8 9 10 8 12 9 8 10 11 Example Output 6 8 8 9 5 Real queries REAL QUERY: 4 3 6 REAL QUERY: 0 1 2 REAL QUERY: 0 1 2 REAL QUERY: 0 4 1 REAL QUERY: 1 3 2 Example Input 2 6 9 3 2 7 4 5 13 2 6 3 11 10 14 17 18 18 16 23 26 19 18 17 18 19 21 14 13 12 Example Output 2 7 7 11 16 18 18 16 14 11 Real queries 2 REAL QUERY: 3 2 7 REAL QUERY: 3 2 10 REAL QUERY: 5 1 4 REAL QUERY: 0 1 5 REAL QUERY: 1 2 2 REAL QUERY: 2 5 8 REAL QUERY: 1 0 3 REAL QUERY: 2 3 5 REAL QUERY: 0 3 2 Example Input 3 3 4 0 1 8 8 10 13 15 13 4 13 12 8 Example Output 3 8 13 13 10 Example Input 4 6 7 4 3 3 3 6 4 14 9 13 8 15 14 11 13 9 17 16 20 13 14 6 Example Output 4 3 10 10 14 21 15 24 Example Input 5 7 11 3 0 997179154 997179152 997179154 204554238 1926119418 1926119416 1370896084 2521188650 2521188654 3204670819 3213587831 3213587825 2592574673 3142795976 3142795983 3067341340 3369331620 3369331617 3266995941 3544021221 3544021220 3341161807 2952422819 2952422823 3068368185 2952422818 2952422823 3137316850 2952422817 2952422819 2934379046 Example Output 5 997179154 1926119422 2521188648 3213587827 3142795978 3369331616 3544021221 2952422819 2952422819 2952422819 2349523846
34,312
Ada and Kohlrabi (ADAKOHL) As you might already know, Ada the Ladybug is a farmer. She has a garden with kohlrabi. Each kohlrabi has assigned a quality, which is a number (possibly negative, since the kohlrabi might be rotten). Ada wants to gather some kohlrabi so she wants to pick a line such that the sum of kohlrabi on the line is maximal. Can you help her to find such line? Input The first line of input contains 1 ≤ T ≤ 100 , the number of test-cases (anyway note that for biggest test-cases there will be only 1 test-case). The first line of each test-case contains 0 < N ≤ 3000 , the number of kohlrabi. The next N lines contains three integers x, y, q: -10 9 ≤ x, y ≤ 10 9 , -10 4 ≤ q ≤ 10 4 , the coordinates of kohlrabi and its quality (note that no two kohlrabi will grow on same coordinates). Output For each test-case, print the best achievable sum of qualities of kohlrabies on a single line. Example Input 5 4 0 0 1 1 1 1 2 2 1 3 3 1 5 0 0 -10 1 0 2 0 1 3 -1 0 2 0 -1 3 3 0 0 -1 1 1 -2 1 3 -5 2 0 0 666 1 7 -666 5 0 0 1 99999999 0 6 0 99999999 5 -99999999 0 6 0 -99999999 5 Example Output 4 5 0 666 13 Example Input 2 1 7 10 8 -2 9 4 -1 -3 -5 -5 7 5 1 -3 2 -6 5 10 -4 9 7 10 Example Output 2 10 Example Input 3 1 4 -6 0 9 7 4 7 7 -6 -10 -6 7 10 Example Output 3 19 Example Input 4 1 6 -10 -1 -10 8 3 4 0 9 -2 4 -6 1 6 0 10 -6 1 -10 Example Output 4 14
34,313
nth number (THREENUMBERS) Given two numbers a and b, you have to find n-th number which is divisible by a or b. Input First line contains an integer T (≤ 100000), denoting number of test cases. Second line contains 3 positive integers a, b and n. (a, b ≤ 10000, n ≤ 1000000000) Output Print n-th number in a new line. Example Input: 1 2 3 10 Output: 15
34,314
Ada and Harvest (ADACROP) As you might already know, Ada the Ladybug is a farmer. She has a very long furrow with many kinds of vegetables (represented by integer numbers). Whenever she wants to harvest a single vegetable, she always replace it with another vegetable (possibly same kind). After each replacement, she wants to know the number of vegetables of the same kind (at the new vegetable) which are before it (have lower position in furrow). Input The first line of input contains 1 ≤ N, Q ≤ 2*10 5 , the length of furrow and number of harvests. The next line contains N numbers 0 ≤ A i ≤ 10 9 the kind of vegetable which is currently on i th spot in furrow (indexed from 0). The next Q lines contains two numbers 0 ≤ i < N (the index of harvested plant) and 0 ≤ a ≤ 10 9 (the kind of newly planted vegetable) Output For each harvest, print the number of vegetables of the same kind before the newly planted vegetable. Example Input 5 5 1 2 1 2 1 2 2 4 2 2 3 3 3 4 3 Example Output 1 3 0 1 2 Example Input 2 10 10 2 3 5 3 9 3 5 2 9 9 7 2 0 5 0 2 1 2 9 2 4 3 8 2 4 2 2 5 3 5 Example Output 2 1 0 0 1 3 1 3 2 0 1
34,315
Billi and Kaddu (BILLI) Bubbleworld is in trouble and our Wonderwoman, Billi needs to rescue the prince so as to save the kingdom from the wrath of the monster Kaddu. To do this, she needs to choose  K  words from a pot of  M  words she stole from Kaddu, and convert them to magical words, which she would use as a spell to break into the prison. She already knows  N  magical words. The conversion of a stolen word to magical word requires the following operations: Remove a character from the end of the word, which incurs a cost of  A  coins Add a character to the end, which incurs a cost of  B  coins. Help Billi save the kingdom by minimizing the cost required to convert  exactly K  stolen words to magical words. Input First line of every test file contains the number of test cases, T. For each test case, first line contains 5 integers: A, B, K, N, M The next N lines contain a string each, denoting the set of magical words known to Billi. The next M lines contain a string each, denoting the set of words stolen from Kaddu. Constraints T ≤ 20 1 ≤ N ≤ 10000 1 ≤ M ≤ 10000 1 ≤ K ≤ M 1 ≤ A, B ≤ 1000 Length of each string ≤ 100 The strings consist of only lowercase characters. Output For each test case, print the minimum cost for the task in a single line. Example Input 2 2 3 1 1 1 abc bca 2 3 2 5 4 harry potter abcde qqwweerr ab abc abcd qqwwweer putter Output 15 5
34,316
Ada and Digits (ADADIG) As you might already know, Ada the Ladybug is a farmer and she also loves math. One day, as farming is sometimes very notorious work, she was thinking about numbers. She was wondering about how many numbers there are having exactly same digital sum as digital product. She have found out some answers for small N (sum & product), but then the numbers started getting big. Can you help her to find out the answers for bigger sums to satisfy her mind? Input The first line contains a single integer 1 ≤ T ≤ 100 , number of test-cases. Each of the next line contains a single number 1 ≤ N ≤ 3*10 5 , the required sum (and so the required product). Output For each test-case, print the number of existing numbers. Since this number might be pretty huge, output it modulo 10 9 +7 ( 1000000007 ). Example Input 8 1 2 3 7 8 12 16 144 Example Output 1 1 1 1 23 240 1091 243368058
34,317
Ada and TicTacToe (ADAQUBIC) Ada the Ladybug was playing 3D Tic-Tac-Toe against her good friend Velvet Mite Vinit. They were playing on 3x3x3 field. Sadly, Vinit had to go home earlier so the game was left unfinished. Ada wants to know who would win the match (if they both played optimally). You also know that Ada started. Input The first line contains a single integer 1 ≤ T ≤ 1000 , number of test-cases. Each test-case will contain 9 lines with three character each, representing the field ( '.' for empty place, 'x' for move of Ada and 'o' for move of Vinit). You are assured that the game is unfinished and valid. First three lines represent the top field, the next three lines represent middle field and the last three lines represent the bottom field. There will be a blank line before each test-case. Output For each test-case, print the name of winner ( Ada or Vinit ); Example Input 7 ..o o.x xox x.x ... x.o ... o.o .x. .x. ... ..o o.x x.. ..o ..x ... ... o.. ... o.x .x. ... .x. o.o .xx oox ..x ..x .o. ..x ..x xo. o.. ..o ... ... ..x ..x .o. ..x o.. ... ... x.o ... ..x ..o ... ... xo. ox. ... .ox o.. x.. ... oxx ..o .ox ..o .x. .x. Example Output Vinit Vinit Ada Vinit Ada Vinit Vinit Example Input 2 1 xox x.o oox o.o x.x xxo x.o oxo ox. Example Output 2 Ada
34,318
Ada and Contact (ADAPHONE) You might already know that Ada the Ladybug has some friends who live on a plum tree . Those friends are numbered from 1 to N (where N is the number of her friends). Ada freely travels on the tree from one friend to another. As she passes a friend (with ID i ), he/she always tells her " Hey Ada! If you meet i+1 or i-1, please give him my phone number. ". Also note that as long as someone obtains phone number of someone else, he distributes it to all friends whose number he/she has. Ada will undertake many walks on the tree (from one friend to another) and she ask you (for each walk), how many independent sets of friends she will make during her walk. The two sets are independent if nobody from one set has a number of someone else in the other set (and vice versa). NOTE: All walks are independent of each other (so no phone-distribution remains from previous walks). Input The first line will contain two integers 1 ≤ N, Q ≤ 2×10 5 , the number of Ada's friends and the number of walks The next N-1 lines will contain two integers 1 ≤ a, b ≤ N , meaning that there is a branch (edge) between a th and b th friend. The next Q lines will contain two integers 1 ≤ a, b ≤ N , meaning that Ada will take walk between a th and b th friend. Output For each query, print the number of independent sets Ada will create by her walk (counting only friends on her path). Example Input 7 6 1 6 1 3 3 5 5 7 3 2 2 4 6 7 1 4 2 5 4 7 3 1 5 5 Example Output 3 1 2 2 2 1 Example Input 2 6 5 1 4 4 6 1 2 2 5 2 3 6 5 6 3 3 5 2 6 4 5 Example Output 2 2 2 2 3 2 Example Input 3 10 10 7 10 2 10 4 10 1 7 8 7 3 10 9 10 5 8 6 2 4 3 7 7 2 5 7 8 7 6 5 2 4 9 7 3 9 6 8 8 Example Output 2 2 1 4 1 3 4 2 3 3 1
34,319
Angry Siam (HRSIAM) You have an array of N problems A . Each problem has a difficulty level. i-th problem has dificulty A[i] . You want to give these problems to HrSiam. But you know, HrSiam doesn't like easy problems, so he will get angry. Also he doesn't want to solve problems with same difficulty again and again. So he also has an array angry , with N elements. When he visits a problem with certain difficulty d , his angriness will increase by d * angry[1] . After some time if he again visits a problem with same difficulty for the second time, then his angriness will increase by d * angry[2] , and so on. Generally, if he visit a problem with certain difficulty d for the i-th time, his angriness will increase by d * angry[i]. In this circumstances, you want to do 2 things - 1. You are afraid that HrSiam may get too angry, so you want to present a part of the array to him. But you need to quickly determine: what will be his total angriness if you present the sub array of problems A[l...r] to HrSiam? 2. After certain time you may want to change difficulty of a problem, i.e set difficulty of x-th problem to y . Input First line there will an integer N , the number of problems you have. Next line will contain the difficulty of the problems, the array A[].  Next line will contain the array angry[], of length N . Next line, there will be an integer Q , the number of queries you want to make. Next Q lines will describe the queries, in format - t x y If t is one, then you need to find the total angriness of the Subarray A[l...r] when presented to HrSiam. Else you need to set A[x] = y . Constraints 1 <= N, Q, x, y, A[i], angry[i] <= 100000  If x, y is in query of first type, then 1 <= x <= y <= N                                                                                                                                              Output For each query of first type, print an integer: the total angriness of the subarray. Solutions to the queries should be printed in the order they appeared in the input. Explanation of Sample In the first sample, the first query range is [3, 6] , the array elements are {3, 3, 1, 1} . When HrSiam see the first problem with difficulty 3, his angriness will increase by 3 * angry[1] . Then he visit a problem with same difficulty he saw before, for the second time, so add 3 * angry[2] Then 1 * angry[1] and 1 * angry[2] Total = (3 * 1) + (3 * 2) + (1 * 1) + (1 * 2) = 12 Example Input: 8 1 2 3 3 1 1 2 3 1 2 3 4 5 6 7 8 2 1 3 6 1 1 5 Output: 12 14
34,320
N..K..Divide (NKDIV) Mona and her brother Alaa are very smart kids, they love math a lot and they are passionate to invent new games. So after they went back from school they invented a new game called "N..K..Divide". First of all, let's define a function D(m). such that D(m) is the number of distinct primes in the prime factorization of m. For Example D(9) = 1 and D(12) = 2. The rules of the game are simple: The game consists of R rounds. In each round there are two integer numbers n and k. Each round consists of multiple turns. Each player alternately takes turn (starting with the player who won the last round / by Mona in the first round). In each turn the player choose some positive integer m, where 2 ≤ m ≤ n such that n is divisible by m and D(m) ≤ k , then divides n by the chosen m. The first player who cannot make any valid move loses. The player who wins more rounds is declared as the winner of the game (if tie then Mona is considered the winner). So the kids asked their father to run the game for them. For each of the R rounds father gives them two integer numbers n, k and wants to know who will be the winner of this round if they both play optimally (to win the current round). Input The first line consists of a single integer 1 ≤ R ≤ 10 the number of rounds the kids are going to play. Each of the next R lines contains two space-separated integers n, k where 2 ≤ n ≤ 10 14 , 1 ≤ k ≤ 10 . Output Print R+2 lines. For the first R lines, the i'th line of them should contain the name of the winner of i'th round if both players play optimally "Mona" or "Alaa" (without quotation marks). The line number R+1 is an empty line. In the last line print the name of the winner, print "Mona" if Mona is the winner of the game otherwise print "Alaa" (without quotation marks). Example Input: 5 3 4 6 2 6 1 9 1 18 2 Output: Mona Mona Alaa Alaa Alaa Alaa
34,321
Mahammad and strings (SORTOUT) Professor Mahammad was busy with working their machine learning project in XYZ University. His team collected many data for the analysis of specific procedures. As the length of individual data objects were quite large, he used a popular hashing technique for getting a unique identifier for each data. Unfortunately, the hashing function generated similar result strings for data. As it is not suitable for the project, he started to think what to do with those strings. Suddenly, he came up with a new idea for a problem for beginners. Now he asks, for the given strings in each query, how many lexicographically smaller or equal strings exist in the input?  Input First line of the input contains two positive integers N and Q, respectively, the number of input strings and the number of queries. The following N lines represent the strings generated from the procedure. Finally, the next Q lines contain the query strings which you need to process. The input section contains strings with only lowercase English letters. Output For each of the Q lines, you need to output the number of equal or lexicographically smaller strings. Note: The sum of the lengths of the input and query strings does not exceed 200000, separately. Example Input: 4 3 fury fuzzy dizzy future fuzz evil freeze Output: 3 1 1
34,322
Match me if you can (STRMATCH) After watching the movie "Catch me if you can" professor Mahammad became very confident about creating a new problem for his programmers. As some procedures in his research heavily depend on string matching, now, he wants to check his beginner programmers' skills in this topic as well. His task is very simple. Professor gives you a random string and several queries. For each of the query string, you have to count the number of its occurrences in the string provided by professor. Input First line of the input section contains two positive integers N and Q, which define the length of professor's string and the number of queries, respectively. Second line contains professor's string having length N (N ≤ 3 000 ) . The following Q lines contain a query string having nonzero length. Output For each of the queries, output the number of the desired count of the occurrences. Note: The sum of the length of query strings does not exceed 500000 . And please, do consider the time limit, because the problem can be solved in both slow and fast languages . Example Input: 7 5 acababa a bb caba aba karp Output: 4 0 1 2 0
34,323
Mean of array (MEANARR) After checking his coders' skills about strings, professor Mahammad wants to analyze how well the coders are familiar with arrays. As the professor is very good at math, he is curious about adding some mathematical background to his new problem. Now, the problem asks you to find the number of subarrays in which the mathematical mean is not less than given K . Mean is the function which defines the average of the corresponding list. More clearly, in order to find the mean of the array, we can divide the sum of the numbers by the number of elements in it.  Input The first line of the input contains two positive integers N and K , the number of elements of the array and the mean, respectively. ( N ≤ 200000 ). The following line contains N integers which represent elements of the array. All the numbers in the input section are 32-bit positive integers. Output Output one integer representing the number of subarrays in which the mean is not less than K . Example Input: 5 4 5 2 4 5 1 Output: 5 Note : The subarrays, satisfying the condition are: [5], [5, 2, 4, 5], [4], [5], [4, 5].
34,324
K-dominant array (KDOMINO) Professor Mahammad was sitting in his garden when an apple fell on his head, and in a stroke of brilliant insight, he suddenly came up with K-dominant notation . An array with length L is called K-dominant , if and only if there is at least one element x lying in the array for which occurrence(x) * K >= L . After analyzing several arrays with this property, professor now, made up a new problem for you. Your task is simple, there are given an array of length N and several queries. For each of the queries, you just need to check whether the subarray [l, r] is k-dominant or not . Input The first line of the input contains two positive integers N and Q , the number of elements of the array and the mean, respectively. ( N, Q ≤ 200000 ). The following line contains N integers which represent elements of the array. The following Q lines contains three integers l , r , and k . ( 1 ≤ l ≤ r ≤ N ). All the numbers in the input section are 32-bit positive integers. Sum of all k's in queries does not exceed 500000. Output For each of the queries, print per line YES or NO if there is an element lying in the subarray which satisfies the condition in the statement. Example Input: 8 3 1 4 2 3 2 2 5 3 2 6 2 1 8 2 1 8 3 Output: YES NO YES Note : For the first and third queries x = 2 satisfies the condition . And for the second query there is no element for which the condition holds true.
34,325
Alien Language (CODWRECK4) Aliens started their journey towards our earth. They some how mastered our English language through a dictionary. However, they were unable to understand the concept of spaces present between words in a sentence. They are continuously sending messages to our earth but it has to be converted to normal form (i.e. if the aliens msg is helloworld it has to be translated into hello world with help of provided dictionary). Scientist believes that these messages consist a very valuable information about how they planning to attack us. And it is guaranteed that aliens communicate only with the words present in the dictionary. This small planet needs your help.... protect it with your skill. Input The first line of the input contains an integer N denoting the size of dictionary. The next following N lines consist of words present in dictionary(all letters are lowercase) The next line of the input contains an integer T denoting number of alien language words that are need to be converted See sample input and output for better understanding Output For each test case, output a single line which contains 2 space separated words that are present in the dictionary. In case of multiple answers make sure the 1st word length to be minimum Constraints 1 ≤ N ≤ 10 5 1 ≤ |W| ≤ 20 1 ≤ T ≤ 1000 1 ≤ |A| ≤ 40 where |W| denotes the length of the largest string present in the dictionary and |A| denotes the length of the string from alien language Example Input: 6 coding code wreck dechef co chef 2 codingwreck codechef Output: coding wreck co dechef
34,326
Ada and Unstable Sort (ADAUSORT) Ada the Ladybug had a lecture about algorithms. She learned that sorting can be done in O(NlogN) time. She also learned concept of stable sort . For those who missed the lecture, it means that as long as there are two equal elements in the array their mutual position won't change after the sort. Ada wanted to come up with something new, so she proposed unstable sort . It is sort with following property: "As long as there are two equal elements in the array their mutual position will change after the sort". As Ada has only theoretical knowledge about it, she has asked you to construct such algorithm for her. Input The first line of each test-case will contain an integer 1 ≤ N ≤ 10 5 , the length of an array. The next line will contain N integers 1 ≤ A i ≤ 10 5 , the elements of the array. Output For each test-case, print N numbers, the indexes of each element on which it was in original array. Indexes start with 1 . Example Input 4 1 2 3 4 Example Output 1 2 3 4 Example Input 3 3 2 1 Example Output 3 2 1 Example Input 6 6 6 6 6 6 6 Example Output 6 5 4 3 2 1 Example Input 5 5 5 2 2 3 Example Output 4 3 5 2 1 Example Input 6 1 2 1 2 1 2 Example Output 5 3 1 6 4 2
34,327
Ada and Friends (ADAFRIEN) Ada the Ladybug has many friends. They always celebrate something and Ada has to buy them gifts. It is pretty costly so she have decided to unfriend some of them. What is the maximum of money she can spare? Input The first line of each test-case will contain two integers 1 ≤ Q K ≤ 10 5 , the number of celebrations ( Q ) and the maximum number of friends Ada wants to unfriend ( K ). The next Q lines will contain s (the name of friend to whom Ada will buy gift) and 1 ≤ E ≤ 10 9 +1 (the expenses). Names will contain at most 40 lowercase English letters. Output For each test-case, print the number of money Ada could spare. Example Input 6 1 uvuvwevwevweonyetenyevweugwemubwemossas 10 ryuk 11 uvuvwevwevweonyetenyevweugwemubwemossas 5 fegla 3 tenshikanade 7 fegla 2 Example Output 15 Example Input 4 3 frodo 1 harrypotter 2 frodo 2 harrypotter 2 Example Output 7 Example Input 7 2 waynebot 7 lhic 4 petr 5 umnik 9 izrak 6 tourist 11 zlobobber 9 Example Output 20 Example Input 6 3 dufresne 5 gump 11 dufresne 3 mcmurphy 19 leon 10 dufresne 1 Example Output 40
34,328
Ada and Subsequence (ADASEQEN) Ada the Ladybug has two string which she wants to give to her friends. As she doesn't want to distinguish between them, she wants to use only some common subsequence. Firstly she wanted to simply use the longest common subsequence but then she realized it wouldn't be kosher . She assigned a positive value to each letter. Now she wants to find the most expensive subsequence. Input The first line of each test-case will contain two integers 1 ≤ N, M ≤ 2000 , the length of each subsequence. The next line will contain 26 integers ( 1 ≤ P i ≤ 10 5 ), the price of each letter. The next line will contain string of length N consisting of lowercase English alphabet. The next line will contain string of length M consisting of lowercase English alphabet. Output For each test-case, print the cost of the most expensive common subsequence. Example Input 4 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 abcd dbca Example Output 2 Example Input 3 3 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 baa aab Example Output 7 Example Input 4 5 1 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 6 zbbz bbzbb Example Output 14 Example Input 3 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 abc def Example Output 0
34,329
Ada and Branches (ADABRANC) Ada the Ladybug lives on a bush. A typical bush consists of some fruits connected with branches. Ada wants to travel between some fruits. Problem is that each edge can stand only some X i weight (so if some creature with more weight would like to travel over the edge, it would break and the creature would fall of the bush). Ada wants to make several travels so she asks you (for each such travel) to how many distinct fruits she can get? Input The first line of each test-case will contain three integers 2 ≤ N ≤ 10 5 , the number of fruits, 1 ≤ M ≤ 2*10 5 , the number of edges and 1 ≤ Q ≤ 3*10 5 , the number of queries. The next M lines will contain three integers 0 ≤ a, b < N (a ≠ b) , the fruits which are connected by and edge and 1 ≤ X i ≤ 10 5 . The next Q lines will contain two integers 0 ≤ a < N , the fruit Ada starts in and 1 ≤ Y ≤ 10 5 , her actual weight. NOTE Multiedges are allowed. Output For each query, output the number of fruits Ada can get to. Example Input 4 4 3 1 2 4 2 3 3 3 0 4 0 1 3 1 3 1 4 1 5 Example Output 4 2 1 Example Input 8 10 8 1 3 3 1 2 2 3 5 1 3 4 3 2 4 7 5 6 2 4 6 8 4 7 3 7 0 1 6 0 4 1 3 1 4 0 5 6 6 6 1 2 3 0 4 5 2 Example Output 7 1 1 3 8 7 4 8
34,330
Ada and Trees (ADATREE) Ada the Ladybug is a farmer. She has a long furrow in which she grows trees. Each tree has some weight. The task is simple, she wants to know the biggest tree on some part of the furrow which is not greater than some height H . As Ada asks for this very often, she asked you to write a program for this. Input The first line will contain two integer 1 ≤ N, Q ≤ 3*10 5 , the number trees and the number of questions. The next line will contain N integers 0 ≤ A i ≤ 10 6 , the heights of trees. The sum next Q will contain three integers: 0 ≤ l ≤ r < N , the segment of furrow she is interested in and 0 ≤ H ≤ 10 6 Output For each query output either the size of highest tree lesser/equal to H or output 0 if such tree doesn't grow on given segment. Example Input 9 8 1 5 9 11 9 7 6 2 1 1 6 4 1 6 10 0 8 97 0 8 4 1 4 5 2 6 8 2 8 5 3 3 12 Example Output 0 9 11 2 5 7 2 11
34,331
Ada and Fimbers (ADAFIMBR) Ada the Ladybug is playing a games against her good friend Velvet Mite Vinit. They are playing a game which they call Fimber: There will be a few piles of seeds. In each move, the one who is in move can choose a pile and take K seeds from it, where K is equal to some Fibonacci number. They alternate in their turns. The one who can't move will lose. Fibonacci number will be defined as F 0 =1, F 1 =1, F N =F N-1 +F N-2 As ladies go first Ada starts. Can you determine who will if both will play optimally? Input The first line of each test-case will contain an integer 1 ≤ N ≤ 10 5 , the number of piles. The next line will contain N integers 0 ≤ A i ≤ 3*10 6 , the number of seeds in each pile. Output For each test-case, print the name of winner (so either " Ada " or " Vinit "). Example Input 6 3 3 1 8 3 4 Example Output Ada Example Input 1 10 Example Output Vinit Example Input 4 3 9 5 2 Example Output Ada Example Input 5 10 10 6 8 10 Example Output Ada Example Input 1 4 Example Output Vinit Example Input 4 6 1 7 3 Example Output Ada Example Input 5 7 10 9 3 10 Example Output Ada Example Input 6 4 6 10 9 3 8 Example Output Vinit
34,332
Ada and Digits 2 (ADADIGIT) Ada the Ladybug likes numbers. Her friends know it so they wanted to give her a number as a gift. Sadly, they bought the number in IKEA so Ada has to assemble the number by herself. Now she is in following situation - she has a few digits before herself and she is wondering what number she will create. As she doesn't understand the manual (it is in Swedish) she has possibility to assemble anything. She is not sure yet, anyway her favourite options are to assemble number with the most divisors or the number with the biggest sum of divisors. Can you help her to find such? NOTE: To assemble number from digits, simply choose any permutation of digits. Leading zeroes are perfectly OK but you have to use all the digits. Input The first line of each test-case will contain an integer 1 ≤ N ≤ 9 , the number of digits to assemble. The next line will contain N digits 0 ≤ d i ≤ 9 . Output Output two integers - the number with the most divisors AND the number with biggest sum of divisors. In case there are multiple such numbers, choose the lesser one. As long as you would use leading zeroes, output the number without the leading zeroes. Example Input 1 5 Example Output 5 5 Example Input 3 1 1 0 Example Output 110 110 Example Input 2 3 4 Example Output 34 34 Example Input 5 1 2 3 4 5 Example Output 43512 51324 Example Input 6 2 2 3 3 4 4 Example Output 432432 432432 Example Input 3 4 8 2 Example Output 248 824 Example Input 4 1 3 5 7 Example Output 7315 7315 Example Input 7 1 2 3 4 5 6 7 Example Output 3124576 7516432
34,333
Ada and Plants 2 (ADAPLNTS) Ada the Ladybug is a farmer. She has two furrows with plants. Each plant has some kind (denoted by number). Problem is, that as soon as there is a pair of plants with gcd greater than 1 in distinct furrows none of them will grow. Ada has decided to throw away minimal number of plants so that every remaining plant will grow up. She has asked you to count the maximal number of plants which could grow up. Input The first line of each test-case will contain two integers 1 ≤ N M ≤ 800 , the number of plants and first and in second furrow. The next will contain N integers 1 ≤ A i ≤ 10 6 , the kinds of plants in first furrow. The next will contain M integers 1 ≤ B i ≤ 10 6 , the kinds of plants in second furrow. Output For each test-case, print the maximum number of plants which could grow up. Example Input 3 4 3 4 5 6 30 1 7 Example Output 5 Example Input 4 3 2 2 10 32 4 16 28 Example Output 4 Example Input 5 5 2 6 12 15 18 33 8 2 3 5 Example Output 5 Example Input 3 3 2 27 9 3 4 8 Example Output 4
34,334
Ada and Substring (ADASTRNG) Ada the Ladybug was exchanging gifts with her friend. What a surprise - they gave her string. As they like her very much, they brought her a very long string. The goodness of the string is the number of distinct substrings. As you might already know, each letter has different value so Ada wants to know the number of distinct substrings beginning with each letter. Input The first and the only line line of each test-case will contain a string (formed by lowercase English letters) 1 ≤ |s| ≤ 3×10 5 . Output For each test-case, print 26 integers, the number of distinct substrings beginning on given letter. Example Input aaa Example Output 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Example Input abc Example Output 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Example Input aabbaa Example Output 10 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Example Input acbabca Example Output 10 7 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Example Input gdhgaghjdsahgdahjklflklkfsa Example Output 50 0 0 57 0 10 84 69 0 30 17 18 0 0 0 0 0 0 18 0 0 0 0 0 0 0 Example Input abababababbaaabbabbabababa Example Output 130 123 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Example Input aadsdadfafdfafdfsdfaf Example Output 71 0 0 59 0 40 0 0 0 0 0 0 0 0 0 0 0 0 21 0 0 0 0 0 0 0
34,335
Ada and Football (ADAFTBLL) Ada the Ladybug has many friends who live on a tree . Each of them is fan of a football team. Ada sometimes goes on a trip from one friend to another. If she meets a friend she tells him/her about all previously visited friends who are fans of the same team. The visited friend will gain +1 happiness for each friend Ada told him/her about. Ada is wondering (for each trip) what will be the total gained happiness. Also note that sometimes a friend changes his/her mind and start to support different team. Input The first line two integers 1 ≤ N Q ≤ 10 5 , the number of friends ( N ) and the number of queries. The next line will contain N integers 0≤ A i ≤ 10 5 , the team which i th friend supports. The next N-1 lines will contain two integers 0 ≤ a, b < N , the friends which will be connected by a branch (edge). The next Q lines will be of two kinds: 1 x y ( 0 ≤ x < N , 0 ≤ y ≤ 10 5 ), meaning that x th friend will start supporting team y (instead of the old one). 2 a b ( 0 ≤ a, b < N ), meaning that Ada will travel from friend a to friend b and wants to know the happiness. Output For each query of second kind, output the gained happiness. Example Input 7 8 0 0 1 2 1 1 2 0 1 1 5 1 2 2 4 2 3 3 6 2 4 5 2 0 6 2 1 3 1 1 2 1 2 2 2 4 5 2 0 6 2 1 3 Example Output 3 2 0 2 6 3
34,336
Ada and Jobs (ADAJOBS) As you might already know, Ada the Ladybug has a huge TODO-list. Sometimes she inserts a new job into her TODO-list and sometimes she is wondering whether there is a job (in her TODO-list), which she wants to do now. She doesn't require the whole job to be there, perhaps just a part of it. Can you create a program which would serve her? That means it either inserts a new job into her TODO-list or answers whether there exists a word (in her TODO-list) which is a substring of given word. Input The first line of input contains Q , the number of queries. The next Q lines contains a number 0 ≤ t ≤ 1 and nonempty string s . If t is equal to 0 then it is insertion query, otherwise it is question query. s consists of lowercase characters only. The sum of lengths of queries of both types doesn't exceed 10 6 (that means the total sum of lengths of strings will be at most 2*10 6 ) Output For each query of type 1 , print either YES , if there is already a substring in the TODO-list and NO otherwise. Example Input 12 0 cat 1 dogville 0 dog 1 dogville 1 gooutwithcat 1 gooutwithcrocodile 1 fancyconcatenation 0 crocodile 1 lacoste 1 gooutwithcrocodile 1 catalanreferendum 1 rocodile Example Output NO YES YES NO YES NO YES YES NO
34,337
Ada and Squares (ADASQR) As you might already know, Ada the Ladybug is a farmer. She has a beautiful square field (of size N×N ) in which she grows many beautiful plants. Each plant has some height. She wants to know, for each subsquare (of some defined size K×K ) what is the minimal sized plant in it. As she doesn't want too many information, she only asks you for the sum of all such lowest plants. As it is mentioned above, she doesn't like "too many information" so she also compressed the heights for you. For each of the N rows, you will be given 4 integers x 0 a b c . The rest of the row ( N-1 plants) could be obtained as x i+1 =(x i × a + b) % c . Input The first line will contain two integers N, K : 1 ≤ K ≤ N ≤ 5000 , the size of field and the defined size of subsquare. The next N lines will contain four integers 0 ≤ x 0 , a, b, c ≤ 10 18 ( c ≠ 0 ), which will generate the i th row. Output Output the sum of minimal heights of each subarray of size K×K . As it might be pretty big, output the number modulo 10 9 +7 (1000000007). Example Input 4 2 8 2 9 9 5 7 9 3 9 7 7 5 7 4 7 3 Example Output 6 Real Field 8 7 5 1 5 2 2 2 9 0 2 1 7 2 0 1 Example Input 2 10 8 78 51 99 77 27 95 37 80 76 5 93 32 92 48 56 64 93 17 18 28 70 30 15 73 60 69 36 56 12 11 63 57 18 81 55 60 59 92 68 81 Example Output 2 18 Real Field 2 78 73 49 57 3 21 15 17 42 8 27 42 27 42 27 42 27 42 27 42 76 25 26 31 24 21 6 27 4 17 92 56 56 56 56 56 56 56 56 56 93 3 13 15 21 11 9 3 13 15 70 71 28 52 42 34 13 40 47 38 60 32 4 32 4 32 4 32 4 32 12 24 42 12 24 42 12 24 42 12 18 13 28 43 58 13 28 43 58 13 59 69 17 12 38 0 68 6 53 3 Example Input 3 20 5 2956 1596 6710 2713 2626 2791 1425 3859 1874 6262 3248 2238 5856 4491 7062 2271 2722 1707 9943 7035 403 2209 7057 1975 7211 9708 3898 6949 2426 9144 8440 2974 5034 3983 6243 7717 3877 37 9002 7373 3021 2549 7277 5516 3673 9640 7775 5355 1563 9728 6671 5484 4342 2971 1237 6834 3589 3662 5391 9672 780 6008 5239 304 5095 4370 280 9403 6295 118 822 2545 5649 2519 5412 6501 2901 2829 9801 846 Example Output 3 38811 Example Input 4 30 8 42190820083565085 13910582960072682 404339598526125697 18330389877395687 13136432922739892 360508552206096544 840939247896706683 166851773518294104 195629367891644832 133017412681920741 791801761173755587 953548694494513035 930566226452148080 212263842828807811 175150807852323258 261521670663969864 223183990889228375 549657188306426129 227104892059916771 710982591168543028 622099644118414985 984577533571891185 802914550839341535 577466815316077292 363883415474075556 913215986569797 257759523922291507 129711072317319582 472381530848232370 587974020968388203 95939647385371737 421772367107774947 870958993881230243 98076059799725034 955829596729745763 73827358022047846 50043465537791007 178000244851301580 686791668222702403 230423627799787034 41761070639181344 703749524391633426 575680731101407438 948818018258441027 74006463131502635 534256412790647769 117842073420805101 689203117404347787 720627491787492218 206756570671097114 5074687913252083 402683208709668506 583558162725379851 516050342346753246 792500576162473842 130741479957823970 709539139438259321 132262390506172747 780941668119266465 575886488550729150 518457490774399283 781644026117044419 451050302936677524 319690456859518311 747952274084607955 433194299929591864 829471355224525516 87759356942462111 472230421696663981 150197958929639709 699963373353260575 156451405305679606 379767724942828073 307602673656652612 536339937437228412 450095461910438107 130196535602142550 12133076804665744 944874740331622465 112002748054899251 384924669386020020 895364022010504585 562727215734096434 364228612518853658 2558159832040223 42876494731943717 303029667687965036 370694399470107119 801915657644445462 610444723365908160 304599053734522278 593616674445351229 318887526987442235 390853723621574162 339872209606293879 308835452771750585 476033942116470840 213009419015490269 20470342994674399 282092030038623628 582424275023334455 712867665674241464 17697708714929958 654849385199113364 475223303973240030 425222042042672679 12723252770801578 591938517391534160 538033927835846645 318295777283007977 593613359214212470 772515434523625506 612174705584217229 415458073586196348 508007743847849815 965297054583491903 179981864970425260 975763652798172152 215122546620747273 113899093042760092 Example Output 4 641904340
34,338
Ada and Mold (ADAMOLD) As you might already know, Ada the Ladybug is a farmer. She has a long furrow in which she grows vegetable (while each vegetable is identified by a bloom-value). The more vegetable is in the furrow the bigger risk of mold there is. More specifically the mold-value can be obtained as sum of xor of all pairs of vegetable's bloom-values. Ada has bought a few wooden separators which could possibly reduce the mold-value. It works in following manner: she can put the separators between some plants, dividing the furrow into multiple segments. The mold-value will then becomes the sum of mold-values of all the segments (independently). Can you find the minimal possible mold-value? Input The first line of input contains two integers N, K : 1 ≤ K < N ≤ 5000 , the length of furrows and the number of separators. The next lines will contain N numbers 0 ≤ A i ≤ 10 9 , the bloom-values of vegetable. Output Output the minimal possible mold-value. Example Input 6 1 1 2 3 4 5 6 Example Output 12 Example Input 1 4 3 5 3 5 3 Example Output 1 0 Example Input 2 7 2 5 3 5 3 5 3 4 Example Output21 24 Example Input 3 9 4 1 2 3 4 5 6 7 666 1024 Example Output 3 8 Example Input 4 30 8 629470789 417274987 617986533 841737683 297969800 432044389 708142005 156958893 499363651 434034331 176735187 525172817 747109631 949700868 259681519 357968078 818249370 456939952 450487335 529013233 327250536 90354657 643708145 141755216 656041628 661580907 204072850 469709611 834069223 681347499 Example Output 4 16154467281
34,339
Catering Contracts (CATER) A new government has come to power after the elections in Siruseri and has promptly announced that it is reassigning all catering contracts on its rail network. As is well known, the rail network of Siruseri is organized so that every station is connected to every other station by a unique path. The new scheme requires contractors to bid for a group of K stations at a time. However, the constraint is that all K stations that a contractor bids for must form a connected portion of the network. Having announced this, the government is now scratching its head to figure out how many different combinations of stations contractors can bid for. For example, suppose the rail network is as given below, and contractors have to bid for 3 stations at a time. Then, there are six possible combinations, namely {1, 2, 3} , {1, 2, 5} , {2, 3, 5} , {2, 4, 5} , {2, 5, 6} and {4, 5, 6} . A combination such as {1, 2, 4} , for instance, is not permitted because these three stations are not all connected to each other. 3 4 \ / 2---------------5 / \ 1 6 You will be given a description of the rail network and the number of stations that a contractor has to bid for. You have to compute the number of different combinations of stations that the contractor can legally bid for, following the rule stipulated by the government. Input The first line of input consists of two integer, N and K , where N is the number of stations in the network and K is the number of stations that each bid must contain. The stations are numbered {1, 2, ... N} . The next N −1 lines describe the track segments. Each of these lines contains two integers i and j describing one track segment, where i and j are the stations at either end of the segment. Output A single integer, denoting the number of combinations that a contractor can legally bid for. You should report your answer modulo 10243 . Constraints In all inputs, 1 ≤ N ≤ 2500 and 1 ≤ K ≤ 90 . Example Input: 6 3 1 2 2 5 3 2 4 5 6 5 Output: 6
34,340
Ada and Hose (ADAHOSE) As you might already know, Ada the Ladybug is a farmer. She owns a square field. There is a hose wrapped around each 1x1 sub-field. All hoses are additionally combined into a bigger hose everywhere where they touch (so the water can arbitrarily flow between both of them [or even all four of them]). Each hose has its own flow-per-time attribute. There is a big well (an infinite source of water) above the field and a big sprinkler under the field. Additionally very big hoses (for our case we can consider them infinitely big) are lead from well to top of the field and from bottom to the sprinkler. Your quest is simple: Calculate the maximal total flow-per-time which goes from well to sprinkler. Input The first line of input contains an integer 1 ≤ N ≤ 1000 , the size of field. The next N lines contains N integers 0 ≤ A ij ≤ 1000 , the size of each hose wrapped around. Output Output the maximal flow-per-time achievable. Example Input 3 9 3 2 1 9 3 3 3 9 Example Output 26 Example Input 1 4 2 0 0 2 0 2 2 0 2 0 0 2 0 2 2 0 Example Output 1 8 Example Input 2 8 2 2 0 1 2 1 5 1 5 1 3 7 1 6 3 1 3 8 5 3 6 6 8 8 2 9 6 6 8 2 3 0 5 4 3 9 7 1 0 4 2 5 1 5 2 5 6 5 5 3 8 3 9 8 1 1 8 9 0 8 2 3 1 9 Example Output 2 28
34,341
Amazing Factor Sequence (hard) (AFS3) Let $s_1(n)$ be the sum of positive proper divisors of $n$. For example, $s_1(1) = 0$, $s_1(2) = 1$ and $s_1(6) = 6$. Let $$S(n) = \sum _{i=1}^n s_1(i).$$ Given $N$, find $S(N)$. Input First line contains $T$ ($1 \le T \le 10^5$), the number of test cases. Each of the next $T$ lines contains a single integer $N$. ($1 \le N < 2^{63}$) Output For each number $N$, output a single line containing $S(N)$. Example Input 6 1 2 3 10 100 1000000000000000000 Output 0 1 2 32 3249 322467033424113218863487627735401433 Information There are 6 Input files. - Input #1: $1 \le N \le 10^5$, TL = 2s. - Input #2: $1 \le T \le 60,\ 1 \le N \le 10^{15}$, TL = 10s. - Input #3: $1 \le T \le 25,\ 1 \le N \le 10^{16}$, TL = 10s. - Input #4: $1 \le T \le 10,\ 1 \le N \le 10^{17}$, TL = 10s. - Input #5: $1 \le T \le 5,\ 1 \le N \le 10^{18}$, TL = 10s. - Input #6: $1 \le T \le 2,\ 1 \le N < 2^{63}$, TL = 10s. My C++ solution runs in about 0.85 seconds for each Input #2 - #6. Note Probably, $O(\sqrt{n})$ solutions will not pass. Intended solutions have a running time of about $O(n^{1/3} \log n)$. Time limits are somewhat strict . The answer can be $\ge 2^{64}$. DIVCNT1 is a little easier than this.
34,342
Factorial Modulo Prime (FACTMODP) Find $N!$ modulo $P$. Input The first line contains $T$ ($1 \le T \le 100,000$), the number of test cases. Each of the next $T$ lines contains two integers $N$ ($0 \le N \le 10^{11}$) and $P$ ($2 \le P \le 10^{11}$), where $P$ is a prime. Output For each $N$ and $P$, output $N!$ modulo $P$. Constraints For each input file, It is guaranteed that (the sum of $\sqrt{P}) \le 320000$. Example Input 3 1000 9907 1000000 9999907 10000000000 99999999907 Output 4494 3354924 40583077821 Note Probably, $O(P)$ solutions will not pass. Intended solutions have a complexity of about $O(\sqrt{P} \log{P})$ My solution runs in 0.5 seconds for each input file.
34,343
Find Linear Recurrence (FINDLR) You are given the first $2K$ integers $a_0, a_1, \ldots, a_{2K-1}$ (modulo $M$) of an infinite integer sequence $(a_i)_{i=0}^{\infty}$ that satisfies an integer-coefficient linear recurrence relation of order $K$. That is, they satisfy $$ a_n = \sum_{i=1}^{K} c_i a_{n-i} $$ for $n \ge K$, where $c_1, \ldots, c_K$ are integer constants. Find $a_{2K}$ modulo $M$. Input The first line contains $T$ ($1 \le T \le 4000$), the number of test cases. Each test case consists of two lines: First line contains $K$ ($1 \le K \le 50$) and $M$ ($1 \le M < 2^{31}$). Next line contains $2K$ integers $a_0, a_1, \ldots, a_{2K-1}$ (modulo $M$). Note: $M$ is not necessarily a prime . Output For each test case, output $a_{2K}$ modulo $M$. Example Input 6 1 16 4 8 1 10 4 8 2 64 13 21 34 55 2 27 13 21 7 1 3 1000000007 32 16 8 4 2 1 2 64 13 21 34 56 Output 0 6 25 8 500000004 40
34,344
Ada and Chess (ADACHESS) Ada the Ladybug was playing chess against her good friend Velvet Mite Vinit. They were talking to each other during the game, saying "I will take your figure in next X moves". After the game, this was really bugging Ada so she have decided to give it more thinking. As she can't determine it "that fast", she asked you to make a program which could output the minimal number of moves in which two figures could get to each other (note they they don't have to alternate, so all the moves could be done only by one of the figures). Also note that it is classical 8×8 chessboard. The interesting figures will be: King, Knight, Queen, Tower, Bishop Input The first line of input will contain 1 ≤ T ≤ 3*10 5 , the number of test-cases. Each of the testcases will contain 6 integers f x y F X Y , where 0 ≤ f, F ≤ 4 are the types of figures (0 to 4 standing for King, Knight, Queen, Tower, Bishop in this order) and 0 ≤ x y X Y ≤ 7 , the coordinates of given figures. Output For each test-case output the minimal number of moves get both figures to same "box". In case the figures can't meet, output " INF ". Example Input 5 1 0 0 1 7 7 2 1 3 3 2 5 0 1 0 4 5 5 3 1 1 4 3 3 0 1 2 0 3 4 Example Output 6 2 2 1 2 Example Input 10 2 3 6 1 6 2 3 3 6 3 6 7 4 4 6 4 2 4 3 6 0 4 1 0 3 7 1 3 5 2 0 0 6 1 5 4 0 5 7 3 3 5 0 4 1 4 5 3 3 2 1 3 4 2 0 5 2 0 2 7 Example Output 2 2 1 1 2 3 2 2 2 5
34,345
Ada and Palaces (ADACHES2) Ada the Ladybug was playing chess against her good friend Velvet Mite Vinit. They came up with new figure, called palace . In fact, palace is just tower with king inside. It can attack as king and tower combined: Either anywhere to same column or row or anywhere to adjacent (by side or diagonal) field. Their question is simple: How many ways can N palaces be placed on N×N chessboard so none of them attacks any other. Since this number might be pretty big, output answer modulo 10 9 +7 Input The first line of input will contain 1 ≤ T ≤ 10 5 , the number of test-cases. Each of the testcases will contain single integer 1 ≤ N ≤ 10 7 , the size of chessboard. Output For each test-case output the number of possibilities modulo 1000000007. Example Input 8 1 2 3 7 10 1000 10000 9999999 Example Output 1 0 0 646 479306 711794305 450342414 838796194
34,346
LCM Pesticide (LCMP) N Slovakistan farmers own neighbouring fields alongside a river, forming a straight line. Each field is infested with (possibly zero) pests. Thanks to ingenious Slovakistan science, each species of pest can be assigned a prime number. Each field can then be assigned a positive number, representative of the pests that are infesting it - the prime factorization of this number indicates which pests are present, with the powers of each prime number representing how strongly the field is infested with that pest. Every pesticide can then be assigned a positive number, which is designed in such a way that its prime factorization indicates what pests it can supress, with the powers of each prime number representing how strong infestations of that pest it is able to handle. To aid their farmers, the government of Slovakistan can select a pest, and then pump a pesticide designed specifically against it into the river, completely supressing that species on all fields. However, due to environmental concerns, they will only use one pesticide at a time - when the government switches to a different pesticide, designed against a different pest, the ones previously supressed return to all fields in full force. On top of that, the farmers union can request pesticide to be sprayed on the fields themselves. Since this is done using an airplane, they can only request pesticide to be sprayed on a contiguous segment of fields. Pesticides with higher numbers are more expensive. Now, for each request the government would like to know the cheapest pesticide they can use to supress all pests on all the fields in the requested segment. Input The first line contains two integers 1 ≤ N ≤ 50000 and 1 ≤ Q  ≤ 10 5   - the number of fields and the number of events. The second line contains N integers f 1 , ..., f N  - the numbers assigned to the fields. They will be positive and not greater than 10 5 . Q lines follow, describing events in the order in which they happened. Each event is either of the form 0 L R or 1 P . If the event is of the form 1 P , 1 ≤ P ≤ 10 5 , it means that the government of Slovakistan began pumping pesticide against the pest number P (a prime number) into the river, and are no longer pumping pesticide against the previous pest, if they were doing so. The exception is P = 1 , meaning that there is simply no pesticide being pumped into the river. In the beginning, the government is not pumping any pesticide. If the event is of the form 0 L R , 1 ≤ L ≤ R ≤ N , it means that the farmers requested pesticide to be sprayed on the contiguous segment of fields from the L -th to the R -th, inclusive. Output For each event of form  0 L R , output the smallest number of pesticide which can handle all infestations on the segment of fields from L to R , modulo 10 9 +7 , taking into account that some pests may be supressed due to the government's aid. More formally, output the least common multiple of the numbers f L , ..., f R , after they have had all factors of P from the last 1 P  event removed, modulo 10 9 +7 . Example Input: 10 12 4 2 3 5 6 47 10007 32768 59049 1 0 1 5 0 2 5 1 2 0 1 5 0 2 5 0 6 10 1 3 0 6 10 1 1 0 1 10 0 10 10 0 1 5 Output: 60 30 15 15 772456932 411740567 342852967 1 60
34,347
Ada and Lemon 1 (ADALEMON) As you might already know, Ada the Ladybug is a farmer. She grows a lemon tree . She wants to pick exactly one lemon (which grows on every leaf of the tree). She is wondering how many distinct trees will remain after harvesting exactly one lemon. Tree is different if they are distinct for each permutation of node labels. Note that a single node is counted as leaf too. Input The first line of input will contain 1 ≤ T ≤ 100 , the number of test-cases. Each of the testcases will contain single integer N , the size of tree. The next N-1 lines will contain two integers 0 ≤ a, b < N, a ≠ b , the edges of tree. The sum of N over all test-cases will not exceed 3000 . Output For each test-case output the number of distinct trees after harvesting exactly one lemon. Example Input 5 4 0 1 0 2 0 3 4 0 1 1 3 3 2 6 0 2 1 2 2 3 3 5 3 4 7 1 2 0 1 2 3 2 4 3 5 6 5 9 0 1 1 2 2 3 3 4 4 5 2 6 3 7 4 8 Example Output 1 1 1 3 4 Example Input 2 1 11 6 1 3 6 4 3 2 3 0 6 5 2 10 4 8 1 7 10 9 0 Example Output 2 3
34,348
Ada and Lemon 2 (ADACITRS) As you might already know, Ada the Ladybug is a farmer. She grows a big lemon tree . She wants to pick exactly one lemon (which grows on every leaf of the tree). She is wondering how many distinct trees will remain after harvesting exactly one lemon. Tree is different if they are distinct for each permutation of node labels. Input The first and only line will contain 25 ≤ N ≤ 3*10 5 . The next N-1 lines will contain two integers 0 ≤ a, b < N, a ≠ b , the edges of tree. Output For each test-case output the number of distinct trees after harvesting exactly one lemon. Example Input 25 18 7 16 18 15 18 8 7 1 8 13 15 22 8 14 18 3 18 23 7 10 8 20 1 21 14 19 3 6 3 9 6 11 7 5 15 17 16 12 22 4 10 24 17 0 8 2 19 Example Output 7 Example Input 25 6 17 2 6 1 2 13 6 7 6 3 17 16 17 12 7 21 2 0 3 9 12 20 6 8 13 22 2 14 21 19 21 18 21 11 6 10 13 24 19 4 16 5 1 23 10 15 20 Example Output 10
34,349
Ada and Alley (ADACUT) As you might already know, Ada the Ladybug is a farmer. She has a long alley of trees. She wants the alley to look good so she has decided to make the heights of all trees equal. She has two possible operations: she can either cut the top of a tree, decreasing its height by one (at cost of 1 ) or cut the tree down (at cost of height i ). Input The first line of input will contain 1 ≤ N ≤ 3*10 5 , the number of trees. The next line will contain N integers 0 ≤ H i ≤ 10 9 Output Print the minimal cost to make the height of all trees in alley equal. Example Input 5 1 2 3 4 5 Example Output 6 Example Input 3 1 4 2 Example Output 3 Example Input 4 1 6 1 1 Example Output 3 Example Input 6 7 11 13 1 3 5 Example Output 18 Example Input 7 1 11 4 13 5 10 7 Example Output 21
34,350
Ada and Tomel (ADATOMEL) As you might already know, Ada the Ladybug is a farmer. She grows a tomel tree . Tomel indeed is a very specific tree. Its growing process starts with one root node with a fruit of random flavor. Whenever a next branch grows, it begins to grow from a random node which is already grown up. No growing starts until the branch is fully grown. As a branch fully grows up, a node with fruit with random flavor appears at the end of the branch. As you surely haven't heard word random for a long time, Ada chooses three random paths and wants to find the number of distinct flavors which grow on the union of these three paths. NOTE: Every random mentioned above is really meant to be random with equal probability for each possible values. Input The first line of input will contain three integers N, K, Q : 1 ≤ N, Q ≤ 3×10 5 , 1 ≤ K ≤ 1000 , the number of nodes of tomel tree, the universe of flavors and the number of Ada's questions. The next line will contain N-1 integers 0 ≤ P i < i is the parent of i th node (here i goes from 1 to N-1 ). The next line will contain N integers 1 ≤ F i ≤ K , the flavor of each fruit. The next Q lines will contain six integers 0 ≤ B, E, X, Y, L, R < N , where the pairs of beginnings/ends of the paths are: ( B, E ), ( X, Y ), ( L, R ) Output For each query output the number of distinct flavors which are on the three paths. Example Input 5 2 5 0 0 0 2 1 1 1 1 2 3 2 3 1 1 4 1 0 2 4 2 3 2 1 4 3 1 0 1 3 3 0 3 1 4 2 0 3 4 1 Example Output 2 2 2 1 2 Example Input 7 3 7 0 0 0 1 2 3 1 3 2 2 2 1 1 3 2 3 6 3 5 0 2 6 0 4 2 3 6 3 0 2 0 2 0 4 0 2 0 1 5 5 3 2 6 1 2 0 5 0 6 0 4 5 3 2 0 Example Output 2 3 2 3 3 3 3 Example Input 8 5 7 0 1 0 1 3 0 3 1 1 4 2 3 1 3 1 1 4 2 3 2 4 3 1 4 2 3 6 6 0 0 7 0 6 3 4 2 1 3 4 5 1 0 1 2 1 5 2 4 5 7 6 2 5 1 6 7 2 Example Output 4 4 3 4 3 4 4 Example Input 12 6 10 0 1 0 2 0 4 4 5 6 6 5 5 4 1 5 3 5 3 5 4 6 4 6 3 9 5 3 5 7 10 8 10 11 6 0 11 6 8 11 3 9 9 2 6 4 8 5 6 5 10 0 2 5 9 11 2 3 2 9 2 3 1 6 10 7 5 2 3 1 9 3 3 4 6 3 6 4 3 8 2 5 0 8 Example Output 5 5 5 5 4 5 4 5 4 3 Example Input 20 10 22 0 1 2 0 4 5 3 6 8 2 7 2 9 8 13 2 16 10 16 6 7 3 10 7 2 10 6 7 3 6 1 1 3 9 9 8 2 9 3 4 13 5 0 17 7 0 2 8 6 8 13 9 19 12 14 5 13 12 14 9 19 5 18 6 4 9 12 2 16 0 1 11 14 14 0 11 4 17 5 1 13 7 16 1 7 8 15 7 1 14 12 8 16 9 8 18 1 4 18 14 8 4 2 2 12 4 16 3 5 10 19 1 6 7 16 11 12 11 0 5 18 12 8 14 17 0 18 3 19 10 12 5 6 4 10 18 19 14 3 15 9 3 9 13 19 1 18 0 5 3 18 1 16 9 19 12 1 13 7 0 2 7 13 16 19 0 11 3 13 12 4 Example Output 6 4 8 8 7 7 7 6 8 4 5 6 7 7 7 6 7 7 7 7 6 6
34,351
Ada and Furrows (ADAFUROW) As you might already know, Ada the Ladybug is a farmer. She has multiple furrows in which she grows vegetables. She also never grows multiple vegetables of the same kind in the same furrow. Ada sometime plants a new vegetable, harvest a vegetable or asks for some aspect which two different furrows have in common (described in input). Input The first line of input will contain 1 ≤ Q ≤ 3*10 5 , the number of queries. Each of the next Q lines will contain ? x y : 0 ≤ x, y ≤ 2*10 4 , and ? is one of: + - v ^ ! \ with following meaning: +: Plants vegetable of kind y to furrow number x (note that there will never be multiple vegetables of the same kind in the same furrow) -: Harvests vegetable of kind y from furrow number x (note that there will always be a vegetable of that kind) v: Finds out how many kinds of vegetables there are in furrows x and y . ^: Finds out how many kinds of vegetable are in both furrows ( x, y ) !: Find out how many kinds of vegetables are in x and y BUT not in both of them at once. \: Find out how many kinds of vegetable are in x but not in y Output For each query of the last four kinds, output the proper answer. Example Input 10 + 1 4 ! 0 2 + 0 2 \ 0 2 ^ 0 1 v 2 0 + 2 4 ! 2 0 + 1 0 ! 0 2 Example Output 0 1 0 1 2 2 Example Input 15 + 0 2 ! 0 1 + 1 1 v 0 1 + 1 2 ! 1 0 ! 0 1 + 0 0 v 0 1 ^ 0 1 + 1 3 \ 1 0 \ 1 0 + 1 0 - 1 2 Example Output 1 2 1 1 3 1 2 2 Example Input 10 + 2 1 ! 3 1 ! 3 1 + 1 1 \ 2 0 + 3 1 v 2 3 ! 2 3 - 1 1 ^ 1 2 Example Output 0 0 1 1 0 0
34,352
Ada and Salesman (ADASALE) Ada the Ladybug lives in Bugladesh. It is a very specific country - there are some cities, but since the government doesn't "waste" money, they all lie on one simple path. Ada is working as Traveling Salesman. She travels between cities, buying and selling products. A product has some varying price in each city (same for buy/sale - described later). Ada travels with bike (to avoid payments for travels) so she can carry at most K items at time in her backpack. She is currently in the first city, and she wants to linearly go to last city. She wants to buy/sell items in a way to maximize her profit. Can you help her? The system is following: Ada has a bag which can carry at most K items. She travels cities linearly (from city c to city c+1 ). Ss she is in a city c , she can either immediately move to next city or buy a licence to trade for L c money. For each city it is also given magical constant P c . The buying/selling system is pretty weird. Buying an item in city c while actually having i-1 items in backpack costs P c *i*c%MOD . Similarly selling of an item in city c while actually having i items in backpack is for P c *i*c%MOD . You can buy any number of items in a city and you can also sell any number of items in city. Anyway note that the number of items can't exceed K (and obviously can't be negative). Input The first line of input will contain three integers 1 ≤ N, K ≤ 3000 and 1 ≤ MOD ≤ 10 4 . The next line will contain N integers 0 < L i ≤ 1000 , the cost of licence for each city. The next line will contain N integers 0 < P i ≤ 1000 , the magical constant for each city. Cities are numbered from 1. Output Output the maximal number of money Ada can gain. Example Input 5 1 3 1 1 1 1 1 1 1 1 1 1 Example Output 0 Example Input 5 5 6 1 1 1 1 1 1 1 1 1 1 Example Output 9 Example Input 6 10 11 1 2 3 3 2 1 1 3 2 5 1 7 Example Output 19 Example Input 9 2 20 6 6 6 6 6 6 6 6 6 2 4 6 8 2 4 6 8 5 Example Output 16 Example Input 10 2 20 5 9 3 4 7 5 2 4 7 2 2 1 4 5 4 5 6 3 2 5 Example Output 25
34,353
Ada and Graft (ADAGRAFT) As you might already know, Ada the Ladybug is a farmer. She grows a big fruit tree (with root in 0). There is a fruit on every node of the tree. Ada is competing in grafting competition and this is her masterpiece. The most valuable tree wins the competition. The value of tree is product of values of each node. The value of a node is the number of distinct fruit kinds in its subtree. Can you find the value of Ada's tree? Since this number might be pretty big, output it modulo 10 9 +7 Input The first and line will contain 1 ≤ N ≤ 4*10 5 . The next line will contain N-1 integers 0 ≤ p i < i , the parent of i th node. The next line will contain N integers 0 ≤ F i ≤ 10 9 , the fruit growing on i th node. Output Print a single integer - the value of tree modulo 1000000007 . Example Input 5 0 0 1 1 1 1 1 2 2 Example Output 4 Example Input 4 0 1 2 6 7 2 3 Example Output 24 Example Input 11 0 1 1 1 3 5 2 7 5 4 494052753 959648710 959648710 959648710 494052753 959648710 959648710 959648710 959648710 494052753 959648710 Example Output 32
34,354
Lannister Army (LARMY) "A Lannister Always Pays His Debts." That's true, now here is a chance for you to get paid by Jaime Lannister. In Jaime's army there are total N number of warriors. And all them are standing in a single row. Now Jaime wants to convey a message to his warriors. But it's very difficult to convey a message if warriors are standing in a single row. So, Jaime wants to break that single row into K rows. Such that in each row at least one warrior should be there. Also, there is an amount of unhappiness associated with each warrior x which is equal to : number of warriors in front of x (in his row) whose height is greater than the height of x. And, total unhappiness is sum of unhappiness of all warriors. Jaime wants that his army should be happy as much as possible. Now, Jaime wants you to break the single row into K rows such that total unhappiness should be minimum. Note : You just have to break the row, you are not allowed to change the position of the warriors. Input First line of input contain two integers N and K . Second line of input contain N number of integers, i th of which denotes height of i th warrior standing in that single row (represented as H[i] ). Constraints 1 ≤ N ≤ 5000 1 ≤ K ≤ N 1 ≤ H[i] ≤ 10 5 Output Output the minimum possible value of "total unhappiness". Examples Input: 6 3 20 50 30 60 40 100 Output: 0 Explanation Break as: Row 1 : 20 50 Row 2 : 30 60 Row 3 : 40 100 Input: 8 3 20 50 30 60 40 100 5 1 Output: 2 Explanation Row 1 : 20 50 30 60, Unhappiness = 1 Row 2 : 40 100, Unhappiness = 0 Row 3 : 5 1, Unhappiness = 1 Total = 2
34,355
Ada and Banquet (ADABANKET) Ada the Ladybug is planning two banquets. It is not an easy process since she has many friends. At first, she had a plan to invite all of her friends but the banquet hall is not big enough. Ada wants to make two banquets and invite all friends to only one of them (also note that the number of invited friends to one banquet can't be equal to N due to capacity). Each friend knows some other friends (and this property is always symmetrical). A friend will get one dissatisfaction for each of her friends who will not be invited to same banquet. Can you find the minimal total dissatisfaction? Input The first line contains an integer 2 ≤ N ≤ 900 , the number of friends. Each of next N lines contain N integers A i, j (either 0 or 1 ), where 1 means the i th friend is friend of j th . Note, that the matrix will be symmetrical. Insect is not friend with himself (well .. at least in the representation). Important note (after new studies) 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 10% chance of being friends, so also the adjacency matrix will be generated (very) pseudo-randomly with 10% chance for each edge. Anyway it will be also assured, that the friendship graph will be connected. Output Output the minimum total dissatisfaction. Example Input 2 0 1 1 0 Example Output 2 Example Input 5 0 1 0 0 1 1 0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0 Example Output 2 Example Input 10 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 Example Output 2 Example Input 30 0 0 0 0 0 1 0 0 1 0 0 0 0 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 1 1 0 0 1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 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 Example Output 6
34,356
Ada and Dahlia (ADAHLIA) As you might already know, Ada the Ladybug is a farmer. Beside fruit and vegetable, Ada grows flowers. At the moment she plans to go to a competition with her dahlias. The evaluation of bunch of dahlias is simple: Jury sorts all dahlias by the diameters of blooms and takes the maximal difference between any two adjacent dahlias. This will be the score. The problems is that Ada's flowers are not in sorted order and she wants to know what score she would get if the passes all flowers to jury. To make job easier for you (or at least Ada hopes so), she created a formula which will give you the diameters of blooms (0 to N-1) in actual order: A i+1 =(a*A i +b)%c . Input The first and the only line contains five integers ( N,a,b,c,A 0 ): 2 ≤ N ≤ 4*10 7 , the number of flowers, and 0 ≤ a, b ≤ 10 18 , 1 ≤ c ≤ 10 18 , 0 ≤ A 0 < c Output Output the maximum difference of elements (if they would be sorted). Example Input 10 2 3 31 7 Example Output 8 Example Input 4 4 6 11 6 Example Output 2 Example Input 50 3 11 41 0 Example Output 8 Example Input 1000 666 777 1234567 11 Example Output 10817 Example Input 10000000 612 521 124578541254695 666666 Example Output 230017823
34,357
NT Games (NTG) Katniss Everdeen after participating in Hunger Games now wants to participate in NT Games (Number Theory Games). As she begins President Snow provides her a number k . Then, she has to defend t back to back attacks from Haymitch Abernathy for practice. In each attack Haymitch Abernathy gives two numbers l and r , for defense she has to compute : As she is new to number theory, help her by computing given expression. Input Format First line contain an integer, i.e. k . Second line contain an integer, i.e. t . Each of next t lines contain two integers, i.e. l & r . Constraints 1<= k <=10^5 1<= t <=10^5 1<= l <=10^5 l <= r <=10^5 Output Format For each attack output the value of expression. Sample Input 1 1 1 5 Sample Output 26 Explanation : Just evaluate the expression.
34,358
Taskin and apple tree (TAKIN) Taskin has an apple orchard Every morning he goes to pick apples from orchard. He has a basket which can carry not more than   M  apples. Taskin picks the apples, and puts them into the basket. Taskin goes to each tree and either picks all the apples from that tree or skips that tree. What is the maximum number of apples Taskin can pick? Input In the first line there will be an integer T  number of test cases. For every test case there will be 2 integers in the first line N and M , number of apple tree in the orchard and capacity of basket respectively. Next line contains N integers a 1 a 2 a 3 ... a n  where a i is the number of apples in the i-th tree. T ≤ 10 N ≤ 20 M ≤ 2 × 10 10 A i ≤ 10 9 Output Print an integer, the maximum number of apples. Example Input: 2 5 6 2 1 2 7 8 5 10 1 2 4 4 6 Output: 5 10
34,359
Ada and Game of Divisors (ADAGAME4) Ada the Ladybug is playing Game of Divisors against her friend Velvet Mite Vinit. The game has following rules. There is a pile of N stones between them. The player who's on move can pick at least 1 and at most σ(N) stones (where σ(N) stands for the number of positive divisors of N ). Obviously, N changes after each move. The one who won't get any stones ( N == 0 ) loses. As Ada the Lady bug is a lady, so she moves first. Can you decide who will be the winner? Assume that both players play optimally. Input The first line of input will contain 1 ≤ T ≤ 10 5 , the number of test-cases. The next T lines will contain 1 ≤ N ≤ 2*10 7 , the number of stones which are initially in pile. Output Output the name of winner, so either "Ada" or "Vinit". Example Input 8 1 3 5 6 11 1000001 1000000 29 Example Output Ada Vinit Ada Ada Vinit Vinit Ada Ada
34,360
Ada and Sets (ADASETS) Ada the Ladybug is attending Assertive Club of Mathematicians. On last session, Ada had a fight with her friend Horntail Hansel. Hansel claimed, that if somebody picks a set of binary-vectors of length K , he can generate an infinitely long binary vector, which will have none of the smaller vectors as substring. Ada claimed opposite and now she is preparing a proof, she could pick a set (for any K ), that every such infinite vector will contain at least one of her vectors as substring. Obviously, it is true, since if she picks all 2 K vectors, Hansel's vector will always have at least one of such vectors as substring (and even as prefix). She also wanted to construct such set, to add to importance, but then she realized 2 K is too much, so instead she wanted to construct minimal such set. Can you help her to find the size of such set? Even though it might be lesser, it is still pretty big, so output it modulo 10 9 +7 Input The first line of input will contain 1 ≤ T ≤ 10 6 , the number of test-cases. The next T lines will contain 1 ≤ K ≤ 10 7 , the size of binary vectors Ada wants to generate. Output For each test-case, output the minimum number of binary vectors of length K Ada has to generate, so that Hansel can't make an infinite vector which wouldn't have at least one of Ada's vectors as substring. Output this modulo 1000000007 . Example Input 7 1 2 3 13 666 123456 3141592 Example Output 2 3 4 632 595842408 994717838 244191463 Examples of first 3 inputs: 0, 1 00, 01, 11 000, 001, 101, 111
34,361
Ada and Prime (ADAPRIME) As you might already know, Ada the Ladybug is a farmer. She grows many vegetables and trees and she wants to distinguish between them. For this purpose she bought a funny signs, which contains a few digits. The digits on the sign could be arbitrarily permuted (yet not added/removed). Ada likes prime numbers so she want the signs to be prime (and obviously distinct). Can you find the number of signs with prime number which could be obtained? NOTE: Number can't have leading zero! Input The first line of input will contain 1 ≤ T ≤ 10000 , the number of test-cases. The next T lines will contain 1 ≤ D ≤ 9 , the number of digits on sign, followed by D digits 0 ≤ d i ≤ 9 Output For each test-case, output the number of distinct primes which could be generated on given sign. Example Input 5 1 9 3 1 2 3 5 1 2 0 8 9 7 1 0 6 5 7 8 2 5 1 2 7 3 1 Example Output 0 0 11 283 15
34,362
Ada and Palace Game (ADAGAME5) Ada the Ladybug is celebrating holidays with her good friend Velvet Mite Vinit. They were playing chess all the morning so they have decided to switch games. If you search in your memory (or in SPOJ archive), you'll find out, they invented a new chess-piece: palace . For those, who can't remember the rules of palace (and were not able to find it): The movement of palace is simple - it combines movement of King and Tower . The game they invented is simple: A few palaces are placed onto chessboard. Ada and Vinit alternate in moves. In each move one can choose any palace on chessboard and move it toward bottom-left corner. Moving closer means, that the Manhattan distance from bottom-left corner will decrease. A player who can't make move will lose. Can you decide the winner? NOTE: Two palaces can share a chess-field (they will just stack them above each other). Also note that as Ada is a lady she goes first! Little Warning : The chessboard was a gift from Ada's good friend Flea Feodorv, who is indeed a great programmer yet not as good chess-player, so the bottom-left corner is not traditional "a1" but "[0,0]". Also the upper-right corner is not traditional "h8" but "[2999,2999]". Input The first line of input will contain 1 ≤ T ≤ 3×10 5 , the number of test-cases. The next T lines will contain 1 ≤ N ≤ 3×10 5 , the number of palaces placed on chessboard. Each test-case will contain N lines containing two integers: 0 ≤ x, y < 3000 , the coordinates of palaces. The sum of N over all test-cases will not exceed 3×10 5 Output For each test-case output the name of winner, so either "Ada" or "Vinit". Example Input 5 1 3 2 1 3 3 1 6 6 3 7 4 3 7 1 0 5 4 2 6 9 7 8 2 1 5 5 Example Output Ada Vinit Vinit Vinit Ada
34,363
Ada and Christmas (ADAXMAS) Ada the Ladybug was recently unwrapping presents and guess what? She got a new chessboard from her good friend Flea Feodorv. As he thought "the bigger chessboard the better the chess game will be", he gave Ada a chessboard even bigger than last time: Now the upper-right corner is [999999999,999999999] (10 9 -1). As you might guess, she can't play classical (nor rapid) chess on such board. But as she doesn't want to throw such valuable (well.. at least big) gift away, she's decided to play Palace Game again. She invited her friend Velvet Mite Vinit. As they played this game recently, they decided to expand the rules a little bit. They have decided to play this game with five most important chess-pieces: Rook , Bishop , King , Knight and obviously, the Palace . The game rules are simple: A few chess-pieces are placed onto chessboard. Ada and Vinit alternate in moves. In each move one can choose any piece on chessboard and move it toward bottom-left corner. Moving toward means, that the Manhattan distance from bottom-left corner will decrease and also that none of the coordinates of chess-piece will increase. A player who can't make a move will lose. Can you tell who'll be the winner if both of them play optimally? As Ada is a lady, she goes first. NOTE: Rules are slightly different than in original Palace Game (even though it wouldn't affect the original game, this game might yield slightly different results). Input The first line of input will contain 1 ≤ T ≤ 3*10 5 , the number of test-cases.   The next T lines will contain 1 ≤ N ≤ 3*10 5 , the number of chess pieces placed on chessboard.   Each test-case will contain N lines containing two integers and a character: 0 ≤ x, y < 10 9 , the coordinates of chess-piece and c ∈ {T, B, K, N, P} (stands for rook( T ), B ishop, K ing, k N ight and P alace).   The sum of N over all test-cases will not exceed 3*10 5 Output For each test-case output the name of winner, so either "Ada" or "Vinit". Example Input 10 2 7 0 B 3 4 T 2 6 7 K 9 1 B 3 8 7 B 9 4 K 4 4 T 2 8 5 T 6 5 K 3 1 2 P 6 1 B 4 4 P 2 1 2 B 0 9 K 1 1 9 K 3 5 0 K 0 4 B 9 1 K 3 0 4 K 0 5 K 3 2 K 3 6 4 N 1 2 N 0 7 N Example Output Ada Vinit Ada Ada Ada Vinit Ada Ada Vinit Vinit
34,364
Ada and Primal Fear (ADAFEAR) As you might already know, Ada the Ladybug is a farmer. She grows many vegetables. During past months, her crop was attacked by colony of parasites. Each vegetable was attacked by A i parasites. Ada has only limited answer for this. She bought a few bottles with Primal Fear , which is a mixture against parasites. Primal Fear works in following way: Each Primal Fear bottle has a power assigned to it (which is coincidentally a prime number). If it is applied to a vegetable with N parasites on it, either the N is divisible by its power , then the size of colony is reduced to N/power , or - if the size is not divisible - then it has no effect. Also, as soon as you apply mixture against a colony, the rest of colony will become immune against Primal Fear . Ada didn't know what to buy so she bought one bottle of every possible power . Can you find out the best strategy to fight against parasites? Input The first line of input will contain 1 ≤ N ≤ 1000 , the number of vegetable. The line will contain N numbers 1 ≤ A i ≤ 2000 , the size of colony on i th vegetable. Output Print the minimum sum of sizes of colonies which could be achieved after applying Primal Fear optimally. Example Input 3 2 8 6 Example Output 8 Example Input 4 6 6 6 6 Example Output 17 Example Input 3 7 4 22 Example Output 5 Example Input 3 11 22 17 Example Output 13 Example Input 2 77 11 Example Output 12
34,365
Adrita and Marbles (ADAM1) Adrita loves to play with marbles at home. She has a circular table on her living room. Let it be stuck on the ground and the ground be a 2D space having only 2 coordinates x and y. She knows the equation of the circle to be x^2 + y^2 - px - qy + z = 0 She has N number of marbles of radius 1 unit. The table is not polished and Adrita has some coordinates where she wants to put the marbles. Help her calculating the number of marbles she will place on the table. Consider the thickness of the table is negligible and if the center is on the border of the table the marble is considered to be on the table. Input The first line contains an integer T (1 <= T <= 10) denoting number of test cases and then T set of input follows of which. the first line contains values of p, q, z (1 <= p, q, z <= 10^6) of the equation x^2 + y^2 - px - qy + z = 0 and the next line contains an integer N (1 <= N <= 10^6) denoting the number of marbles Adrita has and then another N lines follows containing x, y ( -10^5 <= x, y <= 10^5) denoting the coordinates of the marbles. Output Print the number of marbles on the table. Example Input: 1 100 250 8125 5 30 10 -100 100 20 5 100 100 -30 10 Output: 1
34,366
Counting Child (CTTC) Little boy Arik is playing with tree. He is counting the number of children of each node. For this, he starts with root node 1. And traverse the full tree in DFS (Depth First Search) style. For simplicity, see the following figure. For Tree - 1, his traversing sequence is 1 2 2 3 3 1. He starts with root node 1. Then he starts visiting first child 2, then finishes his traversing at 2. Then he starts visiting second child 3, then finishes his traversing at 3. And then finally finishes his traversing at 1. For Tree - 2, his traversing sequence is 1 2 4 4 2 3 5 5 6 6 3 1. Input Input starts with an integer t (1 ≤ t ≤ 20), which denotes the case numbers. For each case, you are given n (1 ≤ n ≤ 100) in first line. Next line contains 2n integers denoting his sequences of traversing. All nodes are between 1 to n. The root node is always node 1. Output For each case print the case number in the first line. Following n lines print each node from 1 to n and number of child of the node. Print a blank line after each test cases. See the sample I/O section for more details about output format. Example Input 2 3 1 2 2 3 3 1 6 1 2 4 4 2 3 5 5 6 6 3 1 Output Case 1: 1 -> 2 2 -> 0 3 -> 0 Case 2: 1 -> 2 2 -> 1 3 -> 2 4 -> 0 5 -> 0 6 -> 0
34,367
Jalil Got TLE (JGTLE) Ananta Jalil is a multi talented person. He can make any task possible which is impossible to others. Recently he has learned programming basic. In a problem, he submitted the following solution: #include <stdio.h> int main() { int t; scanf("%d", &t); for(int tc = 1; tc <= t; ++tc) { int a, b, c; scanf("%d %d %d", &a, &b, &c); long long result = 0; for(int i = 1; i <= a; ++i) { for(int j = 1; j <= b; ++j) { for(int k = 1; k <= c; ++k) { result += j * k; } } } printf("Case %d: %lld\n", tc, result); } return 0; } But he got TLE (Time Limit Exceeded) as he is novice in programming. That’s why his solution was not efficient. So you are here to write an optimized solution for Jalil which will give the same output. Input The first line of input will contain a positive integer T denoting the number of test cases. In each test case, there will be 3 positive integers a, b and c. Constraints T <= 1000 a <= 30 b <= 100000 c <= 10000 Output For each test case, print the output as same as the above program. Example Input 3 1 4 3 3 4 2 143 342 777 Output Case 1: 60 Case 2: 90 Case 3: 2535110464887
34,368
Adrita and Her Bike Ride (ADRABR) Adrita, a lady Programmer is at Uttara, at her office. She needs to go home now. But she forgot to take enough money with her. She has limited money, so she can’t afford Uber Ride. She called her friend to give a ride on her bike. But Adrita wants to pay her friend and she wants minimum cost shortest path to reach to her home. There are several points and there are roads connecting the points. All connecting roads are of length of 1 kilometer. Some roads (like flyover) will charge tolls and the tolls are given. You are to find the shortest path based on minimal cost. Consider the cost for 1 kilometer is 12 taka for bike ride. Input In the first line of input, there’s a positive integer k (k <= 50) denoting the number of test cases. In each test case, the first line contains 4 integers N (1 <= N <= 10^5) denoting the number of points, R (1<=R<= 10^6) denoting the number of connecting roads, S (1 <= S <= N) denoting the starting point, D (1 <= D <= N) denoting the destination point. The next R lines contains 3 integers each, U, V (1 <= U, V <= N) and T, (0 <=T <= 10^5) indicating that point U and V are connected with the road which requires toll T taka. All roads are bidirectional and you can assume that the destination point is reachable from the starting point. Output Print the minimum cost to reach her destination. Example Input 1 6 6 1 6 1 2 0 2 3 0 3 4 1 4 5 2 5 6 0 4 6 12 Output 61
34,369
Seetha’s Unique Game (SEUG) There was once a little girl named seetha who loves to play little tricky games. Once she was playing with stones, noticed a rectangular glass box with some water fill in it. She invented a game with a that box. She wants to share the rules of the game with you all. The rules are as follows: You will be given length, width and height of the rectangular box and the amount of water in it. You will also be given the number of stones she has. The weight of stones will be given such as w1,w2,w3, …, wn and each weight will resemble how much water level it can increase in units. If you continuously put stones in that box, at a certain level the water will spill out from the glass box. You have to determine the minimum number of stones needed. Input First line of input contains number of test cases T (T ≤ 10). Second line of input contains three numbers 1 ≤ a, b, h ≤ 1000 and 1 ≤ w ≤ 1000 representing the length, height and width of the box and the amount of water filled in the glass box. In the Third line you will be given 2 ≤ N ≤ 1000 which represents the number of stones she has. Next line of input contains N space separated numbers 1 ≤ wi ≤ 100 which resemble the weight of each stones. Output Print the minimum number of stones needed according to problem statement. Example Input 2 5 3 10 2 6 5 8 1 4 3 2 12 6 22 8 9 2 5 4 2 3 1 2 3 1 Output 2 4
34,370
Ada and Pet (ADAPET) Ada the Ladybug just got herself a new pet. She was thinking about a name for it. She thought-up a beautiful name for it already but now she doesn't think this name is "enough". She wants to find a new name, which will contain the original name at least K times as substring (to emphasize its importance). As Ada doesn't want the pet's name to be too long, she wants to find the shortest one - can you find the length of it? Input The first line of input will contain T , the number of test-cases. Each of the next T lines will contain a non-empty string s , consisting of lowercase English letters and a number 1 ≤ K ≤ 10 6 (the number of times the given name shall be in the new name). The sum of lengths of strings over all test-cases will not exceed 5*10 5 . Output For each test-case print the minimum length of new name. Example Input 8 ada 3 abc 2 r 7 rr 5 gorego 3 abbababbbbababababba 2 abcabcabca 3 lopadotemachoselachogaleokranioleipsanodrimhypotrimmatosilphioparaomelitokatakechymenokichlepikossyphophattoperisteralektryonoptekephalliokigklopeleiolagoiosiraiobaphetraganopterygon 1 Example Output 7 6 7 6 14 36 16 182
34,371
Prefix Square Free Words (PSFWORDS) A string is called a square string if it can be obtained by concatenating two copies of the same string (i.e. $s=uu$ for some word $u$). For example, "abab", "aa" are square strings, while "aaa", "abba" are not. A string is called prefix-square free if none of its prefixes is a square. Chiaki would like to know the number of nonempty prefix-square free strings whose length is less than or equal to $n$. The size of the alphabet Chiaki uses is $m$. As this number may be very large, Chiaki is only interested in its remainder modulo $2^{32}$. Input There are multiple test cases. The first line of input contains an integer $T$ ($1 \le T \le 100$), indicating the number of test cases. For each test case: The first line contains two integers $n$ and $m$ ($1 \le n \le 100, 1 \le m \le 10^9$) -- the length of the string and the size of the alphabet. Output For each test case, output an integer denoting the answer. Example Input: 2 3 2 4 6 Output: 8 1266 Information There are $5$ input files: Input #1: $1 \le T \le 100, 1 \le n \le 10$. Input #2: $1 \le T \le 50, 1 \le n \le 30$. Input #3: $1 \le T \le 30, 1 \le n \le 60$. Input #4: $1 \le T \le 10, 1 \le n \le 80$. Input #5: $1 \le T \le 2, 1 \le n \le 100$.
34,372
Palindrome Maker (PALMKR) One day little girl Lilith was playing with strings. She made a string X which is a palindrome! Suddenly her favorite dog “hehway” came and ate some of the characters from X but not all! Lilith built another palindrome but naughty “hehway” came again and destroyed it! Watching this happening again and again Lilith’s boyfriend Mada thought that he can give her a machine as birthday present that automatically converts any string to palindrome by adding some characters. The machine will be connected with an infinite supply of lowercase Latin characters (‘a’-’z’). The machine also has two amazing features: The machine always adds minimum number of characters to the input string in order to convert it to a palindrome. If there are multiple ways then it always produces the lexicographically smallest palindrome. We all know that machines are not perfect! So, there is no way to guaranty that the machine generated palindrome is the original palindrome that Lilith made in the first place! But, “Mada” thought that it will at least help Lilith to forget the sorrow of losing her favorite palindromes to her favorite dog! So, when you enter a string X into the machine, the machine’s output looks like N Y, where N is number of new characters that it added to X to make Y. And Y is the lexicographically minimum palindrome produced by adding 0 or more characters with X. Can you help “Mada” with the algorithm of the machine? Input: The first line of input determines the number of test cases (1<=T<=2000). Each of the next T lines contains a string S (1<=|s|<=100). S is a string which is left after Lilith’s dog “hehway” ate some of the characters (possibly none!) of the original string. S will be the input of the machine. Output: Print the machine’s output in each line along with the case number! See Sample test cases for I/O format and explanation for more clarification about the problem. Sample: Input: 4 ab aba abcd bca Output: Case 1: 1 aba Case 2: 0 aba Case 3: 3 abcdcba Case 4: 2 abcba Explanation: First input “ab” => We can add a "b" to its beginning which will make it “bab” we can also add an "a" to its end which till make it “aba”. In either way we are adding one extra character but “aba” is lexicographically smaller than “bab”. So our result is “aba”. We can also add “ba” to the end of “ab” which will result into “abba” which is also a palindrome, but in that case we would need two characters instead of one. We need to ensure minimal character insertion at first and then try to minimize the result lexicographically. See this way, (a) + ab + (ba + a) results into “aabbaa” which is lexicographically smaller than “aba” but it needs 4 characters to build that palindrome where “aba” needs only 1. So, “aba” is the desired result! In second case the string is already a palindrome! Look at the fourth case. We are allowed to add character at any position of the given string not only just at beginning or end!
34,373
Chiaki With Intervals (INTDSET) Chiaki has a set $A$ of $n$ intervals, the $i$-th of them is $[l_i, r_i]$. She would like to know the number of such interval sets $S \subset A$: for every interval $a \in A$ which is not in $S$, there exists at least one interval $b$ in $S$ which has non-empty intersection with $a$. As this number may be very large, Chiaki is only interested in its remainder modulo $(10^9+7)$. Interval $a$ has intersection with interval $b$ if there exists a real number $x$ that $l_a \le x \le r_a$ and $l_b \le x \le r_b$. Input There are multiple test cases. The first line of input contains an integer $T$, indicating the number of test cases. For each test case: The first line contains an integer $n$ ($1 \le n \le 2 \times 10^5$) -- the number of intervals. Each of the following $n$ lines contains two integers $l_i$ and $r_i$ ($1 \le l_i < r_i \le 10^9$) denoting the $i$-th interval. It is guaranteed that for every $1 \le i < j \le n$, $l_i \ne l_j$ or $r_i \ne r_j$ and that the sum of $n$ in all test cases does not exceed $2 \times 10^5$. Output For each test case, output an integer denoting the answer. Example Input: 2 3 1 2 3 4 5 6 3 1 4 2 4 3 4 Output: 1 7
34,374
Chiaki With Intervals (Easy) (INTDSET2) Chiaki has a set $A$ of $n$ intervals, the $i$-th of them is $[l_i, r_i]$. She would like to know the number of such interval sets $S \subset A$: for every interval $a \in A$ which is not in $S$, there exists at least one interval $b$ in $S$ which has non-empty intersection with $a$. As this number may be very large, Chiaki is only interested in its remainder modulo $(10^9+7)$. Interval $a$ has intersection with interval $b$ if there exists a real number $x$ that $l_a \le x \le r_a$ and $l_b \le x \le r_b$. Input There are multiple test cases. The first line of input contains an integer $T$ $$, indicating the number of test cases. For each test case: The first line contains an integer $n$ ($1 \le n \le 10^5$) -- the number of intervals. Each of the following $n$ lines contains two integers $l_i$ and $r_i$ ($1 \le l_i < r_i \le 10^9$) denoting the $i$-th interval. It is guaranteed that for every $1 \le i < j \le n$, $l_i \ne l_j$ or $r_i \ne r_j$ and that the number of distinct $r_i$ in each test case does not exceed $15$. Output For each test case, output an integer denoting the answer. Example Input: 2 3 1 2 3 4 5 6 3 1 4 2 4 3 4 Output: 1 7
34,375
Counting Divisors (general) (DIVCNTK) Let $\sigma_0(n)$ be the number of positive divisors of $n$. For example, $\sigma_0(1) = 1$, $\sigma_0(2) = 2$ and $\sigma_0(6) = 4$. Let $$S_k(n) = \sum _{i=1}^n \sigma_0(i^k).$$ Given $n$ and $k$, find $S_k(n) \bmod 2^{64}$. Input There are multiple test cases. The first line of input contains an integer $T$ ($1 \le T \le 10000$), indicating the number of test cases. For each test case: The first line contains two integers $n$ and $k$ ($1 \le n, k \le 10^{10}$). Output For each test case, output a single line containing $S_k(n) \bmod 2^{64}$. Example Input 5 1 3 2 3 3 3 10 3 100 3 Output 1 5 9 73 2302 Information There are 5 Input files. Input #1: $1 \le n \le 10000$, TL = 1s. Input #2: $1 \le T \le 300,\ 1 \le n \le 10^7$, TL = 5s. Input #3: $1 \le T \le 75,\ 1 \le n \le 10^{8}$, TL = 5s. Input #4: $1 \le T \le 15,\ 1 \le n \le 10^{9}$, TL = 5s. Input #5: $1 \le T \le 5,\ 1 \le n \le 10^{10}$ , TL = 5s. My C++ solution runs in 5.6 sec. (total time) Notes This is general version of DIVCNT1 , DIVCNT2 and DIVCNT3 . You may want to solve these three problems first.
34,376
Chiaki Sequence (A001856) Chiaki is interested in an infinite sequence $a_1, a_2, a_3, ...$, which defined as follows: $$a_n = \begin{cases} n, & n \le 2 \\ 2 \cdot a_{n-1}, & n \text{ is odd} \\ a_{n-1}+r_{n-1}, & n \text{ is even}\end{cases}$$ where $r_n$ is the smallest positive integer not in the set $S_n = \{a_j - a_i \mid 1 \le i < j \le n\}$. Chiaki would like to know the sum of the first $n$ terms of the sequence, i.e. $\sum\limits_{i=1}^{n} a_n$. As this number may be very large, Chiaki is only interested in its remainder modulo ($10^9 + 7$). Input There are multiple test cases. The first line of input contains an integer $T$ ($1 \le T \le 1000$), indicating the number of test cases. For each test case: The first line contains an integer $n$ ($1 \le n < 10^{100}$) without leading zeros. Output For each test case, output an integer denoting the answer. Example Input 11 1 2 3 4 5 6 7 8 9 10 1000000000 Output 1 3 7 15 31 52 94 145 247 359 834069170 Information There are $5$ input files and my unoptimized python3 code runs about 1.1 sec per file.
34,377
The Sum of Unitary Divisors (UDIVSUM) A natural number $d$ is a unitary divisor of $n$ if $d$ is a divisor of $n$ and if $d$ and $\frac{n}{d}$ are coprime. Let $\sigma^{*}(n)$ be the sum of the unitary divisors of $n$. For example, $\sigma^{*}(1) = 1$, $\sigma^{*}(2) = 3$ and $\sigma^{*}(6) = 12$. Let $$S(n) = \sum_{i=1}^n \sigma^{*}(i).$$ Given $n$, find $S(n) \bmod 2^{64}$. Input There are multiple test cases. The first line of input contains an integer $T$ ($1 \le T \le 50000$), indicating the number of test cases. For each test case: The first line contains an integer $n$ ($1 \le n \le 5 \times 10^{13}$). Output For each test case, output a single line containing $S(n) \bmod 2^{64}$. Example Input: 7 1 2 3 4 5 100 100000 Output: 1 4 8 13 19 6889 6842185909 Information There are 8 Input files. Input #1: $1 \le n \le 50000$, TL=1s Input #2: $1 \le T \le 1000, \ 1 \le n \le 5 \times 10^7$, TL=5s Input #3: $1 \le T \le 300, \ 1 \le n \le 5 \times 10^8$, TL=5s Input #4: $1 \le T \le 80, \ 1 \le n \le 5 \times 10^9$, TL=5s Input #5: $1 \le T \le 30, \ 1 \le n \le 5 \times 10^{10}$, TL=10s Input #6: $1 \le T \le 10, \ 1 \le n \le 5 \times 10^{11}$, TL=10s Input #7: $1 \le T \le 3, \ 1 \le n \le 5 \times 10^{12}$, TL=10s Input #8: $T=1, \ 1 \le n \le 5 \times 10^{13}$, TL=10s My unoptimized C++ solution runs in 8.9 sec (total time). And with some constant optimization, now my C++ solution runs in 1.03 sec (total time).
34,378
Just a Palindrome (JUSTAPAL) A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. Chiaki has a string $s$ and she can perform the following operation at most once: choose two integer $i$ and $j$ ($1 \le i, j \le |s|$). swap $s_i$ and $s_j$. Chiaki would like to know the longest palindromic substring of string after the operation. Input There are multiple test cases. The first line of input contains an integer $T$, indicating the number of test cases. For each test case: The first line contains a non-empty string $s$ ($1 \le |s| \le 10^6$) consisting of lowercase and uppercase letters. It is guaranteed that the sum of all $|s|$ does not exceed $10^6$. Output For each test case, output an integer denoting the answer. Example Input: 10 a xxxx ssfs aaabbacaa missimxx ababababgg dfsfsdgdg asdsasdswe chiaki teretwer Output: 1 4 3 8 6 9 6 9 3 6
34,379
Prime Pesticide (PRIMEP) N  Slovakistan farmers own neighbouring fields alongside a river, forming a straight line. Each field is infested with (possibly zero) pests. Thanks to ingenious Slovakistan science, each species of pest can be assigned a prime number. Each field can then be assigned a positive number, representative of the pests that are infesting it - the prime factorization of this number indicates which pests are present, with the powers of each prime number representing how strongly the field is infested with that pest. The resulting number indicates how much damage is done to the crops on that field. To help the farmers, the government is planning to spray pesticide on some contiguous segment of fields. Due to environmental concerns, the pesticide can only be effective against a single species of pest. However, what segment of fields to spray and with what pesticide has given rise to a huge debate in the parliament - there simply isn't enough data to decide. Given Q proposals L R p , meaning that pesticide against the pest assigned prime number p could be sprayed on fields L through R , find out how much damage to crops it would prevent. Input The first line of input contains two integers N  and Q ( 1 ≤ N,Q ≤ 500,000 ): the number of fields and the number of proposals. The second line contains N numbers f 1 , ... , f N - the numbers assigned to the fields. They will be positive and not greater than 10 6 . Q lines follow, each containing three numbers L R p  ( 1  ≤ L ≤ R ≤ N, 1 ≤ p  ≤ 10 6 ,   p   is a prime number), meaning that the government proposes to spray pesticide against pest p on fields [ L,R ] Output For each proposal L R p , output how much crop damage is mitigated; that is, output  ( f L  + ... + f R  - f ' L  - ... - f' R   ), where f ' i is f i   after all factors of p  have been removed from it. Example Input: 5 5 10 20 30 40 50 1 1 2 1 5 5 1 5 47 2 4 3 2 4 2 Output: 5 128 0 20 65 In the fourth proposal, the result is (20 + 30 + 40 - 20 - 10 - 40) = 20.
34,380
Gray Code and Twos Complement (GCATC) Let $x$ is a binary number with $n$ digits ($a_na_{n-1}a_{n-2}...a_2a_1$). And we can encode it as $G(x) = x \oplus \lfloor \frac{x}{2} \rfloor$ or as $C(x) = (2^n - x) \bmod 2^n$, where "$\oplus$" is bitwise XOR operation and "$\lfloor x \rfloor$" indicates the largest integer which is not greater than $x$. For some reasons, Chiaki encodes her password $P$ into $G(P)$ and $C(P)$. Then she writes $G(P)$ and $C(P)$ in a paper. However, something terrible happened. A bug ate some parts of the paper, so some digits are unreadable now. Chiaki is so worried that she want you to determine the values of these digits using the readable digits. Input There are multiple test cases. The first line of input contains an integer $T$, indicating the number of test cases. For each test case: There are $2$ lines of same number of digits describe $G(P)$ and $C(P)$. In every line, it only contains '1', '0' and '?'. Unreadable digits are denoted with symbol '?'. Digits are given from the most significant digit to the least significant digit. It is guaranteed that the sum of all $|G(P)|$ does not exceed $10^6$. Output For each test case, if it is impossible to restore $G(P)$ and $C(P)$, you should output "IMPOSSIBLE" (without the quotes). If $G(P)$ is unique, you should output "UNIQUE" (without the quotes) in the first line. Then output restored $G(P)$ and $C(P)$ in the same format. If there are two or more possible $G(P)$ that can be restored using the readable digits. You should output "AMBIGUOUS" (without the quotes) and the number of possible $G(P)$. The number may be very large, so the answer should modulo $10^9 + 7$. Example Input: 3 1110 0101 11?? 01?? 111? 100? Output: UNIQUE 1110 0101 AMBIGUOUS 3 IMPOSSIBLE
34,381
Tower of Hanoi Movement - Hard (TOHMOVE2) The easier version of this problem can be found here The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower and sometimes pluralized) is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: Only one disk can be moved at a time. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack. No disk may be placed on top of a smaller disk. With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2 N − 1, where n is the number of disks. The description is retrieved from Wikipedia From the description above, AVM wants to know the a th step of optimal solution. The set of Tower of Hanoi consists of N disks and 3 rods (A as the source rod, B as the spare rod, and C as the target rod). Input The input file consists of several lines. The first line contains a single number T representing the number of test cases. The next T lines contains N and a representing the number of disk and the a th move. Output The output file should contains T lines. The i -th line should contain P : A => C , the P th disk, the rod of P th disk before the movement, and the rod of P th disk after the movement. Constraint 1 <= T <= 1000 1 <= N <= 50 1 <= a <= 2 N - 1 Example Input: 3 2 3 3 5 3 7 Output: 1 : B => C 1 : B => A 1 : A => C Explanation The 2-disks Tower of Hanoi optimal solution is: 1 : A => B 2 : A => C 1 : B => C Therefore, the first test case answer is 1 : B => C The 3-disks Tower of Hanoi optimal solution is: 1 : A => C 2 : A => B 1 : C => B 3 : A => C 1 : B => A 2 : B => C 1 : A => C Therefore, the second test case answer is 1 : B => A and the last test case answer is 1 : A => C
34,382
Bucket Selection (SELECTION) After a long period working in his magical garden, Bratan Mahammad could grow flowers of N distinct kinds there. Since Tukezban's (Mahammad's love) birthday is coming, as a perfect gift, Mahammad wants to give her K bunches of flowers. Interestingly, each flower has a beautifulness x i and the number of flowers of every kind is M . When preparing flower buckets, he has to be very careful: every bucket must consist of N flowers and surely, all flowers have to be distinct kind in each bucket. The overall beauty value of K buckets depends on the absolute difference between the beautifulness of the most beautiful flower of K buckets ( max(x i ) ) and the least beautiful one ( min(x i ) ). Help Mahammad minimize this difference. Input The first line of the input contains 3 positive integers, N , M and K , denoting the number of flower types, the number of flowers in each type, and the number of buckets needed, respectively. Then, the following N lines have 4 integers each, x i,1 , a i , b i , c i . Here x i,1 indicates the beautifulness of the first flower in i-th type. And for remaining M - 1 flowers, beautifulness value is calculated as x i, j = (a i * x i, j -1 + b i ) % c i . You can safely assume that N, M, K ≤ 2500 and K ≤ M . All numbers in input section fit 32-bit signed non-negative integers. Output Print the minimum possible difference in K-buckets . Example Input: 2 3 2 2 2 3 9 2 1 2 10 Output: 4 Note: The generated beauty values will be: For i = 1: (2, 7, 8) For i = 2: (2, 4, 6) One optimal way is to choose buckets as (7, 4) and (8, 6) together, so the difference is |8 - 4| = 4 By the way, we should not choose (2, 4) and (7, 2), since |7 - 2| = 5, which is greater than 4.
34,383
"Operation - Modulo" (OPMODULO) Mahmud solved some easy math problems from SPOJ and called himself king of number theory. GodFather GodMATHer Rashad heard it and got angry, so he kidnapped Mahmud. Rashad gave him a task called "Operation - Modulo". Mahmud must solve this task, you know what will happen otherwise ;(. In the Operation - Modulo, we define a function f(n) = (n mod 1) + (n mod 2) + (n mod 3) + ... + (n mod n) , where n mod x denotes the remainder when dividing n by x . Rashad interests with integers n such that f(n) = f(n - 1) , so he gave Mahmud two numbers L and R , and demands him to find the sum of all integers n such that L ≤ n ≤ R and f(n) = f(n - 1) . Input First and the only line of input contains two positive integers, L and R (1 ≤ L ≤ R ≤ 10 18 ) . Output Print the demanded sum in one line. Example Input: 1 3 Output: 3 Note: I hope you proved your solution before submitting it :)
34,384
Agent prefix (AGPREFX) You have been recruited by a top secret intelligence organization. Now, finally, your dream of becoming a secret agent has come true. This agency is so secret that no one even knows its name... and it must stay that way! Your first task is to to eliminate the name of your agency from the text messages that agents of other agencies exchange. Unfortunately, not even you can know. To do this someone will tell you the name and where it is in the text. Your job is to replace that word with the word LUISS. Good luck Agent Prefix! Inputs Input will come to you over three lines. The first will contain the name of the agency to be eliminated, the second the first index of the string in which to replace the word, the third the message Outputs The output should be the string in the third line with the word in the first line replaced with LUISS Example Input: agenzia 7 Questa agenzia domina il mondo Output: Questa LUISS domina il mondo
34,385
Huseyn and his game (HUSGAME) Once our hero Huseyn invited Ziya the ProGrammer ProGamer to play his new game with him. Ziya has a great prestige in the gamers area, so he must win the game or ignore the invitation to save his reputation. The rules of the game are not difficult: Initially, there are N stones on the table. Huseyn will start the game and they will play alternatively. Each turn consisting of replacing the number of stones n on the table with n-1 or [(n+1)/2] . Here [] is floor function. The player who makes 1 stone remain wins. As Ziya is busy with playing games (you know, he can't pause online games :P) you need to make an honest decision for him. Input There will be multiple test cases. The first line of the input consisting of the number of the test cases - T (1 ≤ T ≤ 10000) . For each test case, there will be only one line donating single integer - N (1 ≤ N ≤ 10 18 ) . Output For each test case, print "ZiYES" if Ziya can win the game without matter of the Huseyn's moves, "HuseyNO" otherwise. Example Input: 3 1 2 3 Output: HuseyNO HuseyNO ZiYES
34,386
Signpost reading (SIGNPOST) Examples Input: The hero was deep inside the dragon's lair. But he was not afraid; he knew what was coming. Each dragon layer has some crossroads. At each crossroad, one can go either left or right. At each crossroad there is a signpost, indicating what is to the left, and what is to the right, always in the same format. One direction leads to the dragon. If the hero, in full armour, went into the dragon's bedroom, he would surely wake him up and become breakfast in bed. So, the hero will definitely choose the other option. The hero always reads this signpost into a single line, by itself. Oh, here comes the first crossroads, thought the hero to himself. Left to dragon. Right to princess. Oh no, what is this sorcery!? What heroes don't know, is that the signposts are cursed. Whoever reads one, forgets which of the two options he definitely didn't want to pick. So the hero needs your help - Every time he manages to read a signpost, tell him where he needs to go. Output: Right, to the princess! Input: The story contains at most 100 lines, none of which are over 100 characters long. The signposts are always read into a single, separate line, and strictly follow the following format: Left to x. Right to y. Where x,y are non-empty strings made up of letters of the english alphabet, one of them is 'dragon', and the other is NOT 'dragon'. This line has no missing, or extra, spaces. Notice that the above example is not a valid signpost, as it violates 'one of x,y is dragon'. Often, heroes just mentally prepare for the inevitable signpost they will face. Right to dragon. Left to princess. Hm, on a real signpost the directions would probably be the other way around, thought the hero. Wait, what is this before me!? Left to dragon. Right to goodluck. Left to youwillneedit. Right to dragon. What is happening!? Where should I go??? Left to havefun. Right to dragon. Output: Right, to the goodluck! Left, to the youwillneedit! Left, to the havefun!
34,387
Game Store (GMSTRE) This day is a very special day, especially for all gamers around the world. The clock now is showing at 8 am and the queue in front of the game store is getting crazy. It is like a hundred of people standing in a line waiting for something big. Then what is that ? Yes, of course the people are going to buy the very new game, just released yesterday. It is the first first-person shooting (FPS) game with very incredible price. Brembo, one of the skillfull FPS gamers, of course he doesn't want to miss this. He also buys the game and then plays the game. After one hour playing the games, Brembo feels that the game is very difficult, but sometimes is very easy. He doesn't feel good about that, and decided to replay the game from the beginning. However, now he wants to play the game in more balanced ways. He first plays the easy-difficulty levels and then go harder until the he reaches the hardest-difficulty level. Poor Brembo, he finds out that the levels are placed randomly and gets confused on choosing the levels. You as his friends, called by Brembo to help him out. There are N levels in the game. Basically, in every level you are given the information about some specific elements. You will notice the bar under the map's levels that contain the information. First, is the number of Health Pack that will be placed in a level. Second, is the number of enemies in a level. And third, is the number of ammo available in a level. A level is said to be easier than another level if it follows these priority, it has more Health Pack, less enemies, and more ammo. Now, you are about to analyze the situation based on the description above. Given the information of N levels, find the easiest and the hardest level based on the information. Since you are Brembo's best friend, you don't want to make him disappointed and you will help him. Input The first line of input is N, the number of levels in the game. (1 <= N <= 100) The next N lines contain three integers separated by space Hi, Ei, Ai, represent the number of Health Pack, enemies, and ammo for i-th level. ( 1 <= Hi,Ei,Ai <= 10000) It is guaranteed that every level has different information. Output The output contain two lines or one line if there is only one level. First line : "Easiest is level a" (a for the level number) Second Line : "Hardest is level b" (b for the level number) Print them without quotes. Example 1 Input: 4 3 2 3 3 4 1 1 4 5 2 2 2 Output: Easiest is level 1 Hardest is level 3 Example 2 Input: 1 2 3 1 Output: Easiest and Hardest is level 1
34,388
Traffic Planning (TRFPLN) Most of the traffic accidents occur at road intersections. In order to deal with the traffic accidents efficiently, the traffic police should arrive at the accidental scene quickly. You, as an urban planner, are entrusted to select the best location in the urban area to build the traffic police station. You are given N coordinates (X i , Y i , Z i ) , where X, Y describe the 2D position and Z is  the height of terrain, representing those road intersections that always have traffic accidents. To simplify the problem, best location means a given road intersection(s) that minimizes the sum of distances to all other given intersections. That is, you will choose a given road intersection(s) as potential location to build the station. Please note that the traffic police can only move along the road horizontally and vertically, but not diagonally which will be blocked by buildings. The length of each street block is 1, and all roads are connected in grid pattern. Input The first line of input is the number of test cases T . (1 ≤ T ≤ 50) For each test case, the first line is the numbers of road intersections that always have traffic accidents N . (1 ≤ N ≤ 1000) The following N lines are the coordinates of each road intersection X i Y i Z i . (-1000 ≤ X i , Y i  Z i   ≤ 1000) It is guaranteed that no coordinates are duplicate. Output For each test case, output the coordinates X Y Z of selected road intersection(s) to build the traffic police station. If there is more than one best location, output all of them according to the input order line by line. After each test case, print a blank line. Example Input: 2 7 2 6 3 1 -5 0 -100 -10 3 3 3 3 0 150 9 999 -3 0 878 123 4 2 -5 -10 0 0 -10 0 Output: 3 3 3 -5 -10 0 0 -10 0
34,389
Map Exploration Cost (MAPEXC) Duck is a young boy who likes to explore the world. Recently, he found an underground place on the Internet and plans to visit. But it is not an easy task because he will have to excavate a tunnel which is a very physical work. Whenever Duck moves one unit, his energy is reduced by one unit, so the exploration cost is increased by one. Luckily, there may be exactly one (or no) existing tunnel or underground space, in this case, Duck can move inside that region without excavating, hence no exploration cost is increased. You are give an underground map, which is represented as a matrix of N rows and M columns. The matrix consisting of ' # ' (Rock, visit to there requiring excavation and increase 1 cost), ' . ' (existing tunnel or space, move between them without increasing cost), ' S ' (Starting point), and ' F ' (Destination). For example, from # to # / # to . / . to # / S to . / S to # / . to F / # to F / S to F will increase 1 unit of cost, only from . to . will increase no cost. Given the maximum cost D , You task is divided into two parts: 1. Check whether it is possible to reach F from S without spending more than D cost. 2. Output the new map, keep showing 'S' and 'F', and the cells that can be visited within the minimum cost required to reach F (inclusive) are represented by '.', otherwises '#'. Because Duck is not allowed to pass through F, in some cases, it is impossible to get to some cells. Those cells will be represented by '#' as well. Initially, the exploration cost at S is 0, and Duck can only move in four directions (Up, Down, Left, Right), no diagonal move is allowed. Input The first line is the number of test cases T. (1 <= T <= 40) For each test case, it starts with three integers N (Number of rows), M (Number of columns), D (Maximum cost). (1 <= N, M <= 200 / 0 <= D <= M + N) The following N lines, each line consisting of M characters, including S, F, either # or . or both, representing the map. It is guaranteed that no two separated tunnels allowed (that is at most one or none), and N and M will not both equal 1. The first line is the number of test cases T . (1 ≤ T ≤ 40) For each test case, it starts with three integers N (Number of rows), M (Number of columns), D (Maximum cost Duck can spend). (1 ≤ N, M ≤ 200, 0 ≤ D ≤ M + N) The following N lines, each line consisting of M characters, either  S , F , # or .  , representing the map. It is guaranteed that no two separated tunnels allowed (at most one, all '.' cells are connected with at least one adjacent edge, or no '.' exists at all), and N and M will not both equal 1. Output For each test case, in the first line, output the word POSSIBLE or IMPOSSIBLE indicating if it is possible to reach F from S within D cost (inclusive). Then, output N lines containing M characters (S, F, #, .) representing the new map, indicating which cells can be visited without exceeding the minimum cost required to reach F, which not necessarily equal D. Print a blank line after each test case. Example Input: 3 8 8 8 ######## #####S## #.###### #...#..# ###...## #####.## ######## #####F## 1 10 6 S####.F### 6 9 4 ######### #S###...# #######.# ##....... ######### ######F## Output: POSSIBLE #....... .....S.. ........ ........ ........ #....... ###....# #####F## POSSIBLE S.....F### IMPOSSIBLE ......... .S....... ......... ......... ......... ......F.. Explanation In case 1, the cost matrix is: 54432123 43321012 32332123 32223223 43322234 54433234 65544345 76655456 We can see that the minimum cost required to reach F from S is 4, which is less than 8, so output POSSIBLE. For the new map, we keep the S and F, and those cells with minimum cost less than or equal to 4 is represented by '.', otherwise '#'.  In case 2, the cost matrix is 0123456-1-1-1 , because we cannot pass through F, but it is impossible to reach the three most right cells without passing through F, so the minimum cost for those cells are both -1.  In case 3, the cost matrix is: 212344445 101233334 212344434 323333333 434444444 545555555 The answer is impossible because the minimum cost at F is 5 which is more than 4. However, no cell has minimum cost more than 5, so they are all represented by '.', except S and F.
34,390
Spaceships in Space (SPA) Aliens attack! Run for your lives! ... or not, it's only a video game. And even then, although alien spaceships are flying straight for the Earth, it's not terribly important to destroy them all. Gregory the Gamer only wants that sweet high score. To be more precise, there are n enemy spaceships, flying in a row. Every spaceship is of one of three colours. Our own spaceship is flying opposite of those, from left to right, and can destroy any of them. Destroying a spaceship of colour i is worth p i points. If you destroy more than one spaceship of the same color in a row, you get more points - second spaceship in sequence is worth 2p i points, for the third one you get 3p i and so on. The maximum number of points you can get for one spaceship is limited by M - if the previous rule dictates more than that, you get exactly M points instead. What is the highest score Gregory can get? Input The first line contains a single integer t , denoting number of testcases. Then, testcases follow. The first line of a testcase contains two integers n , M - number of spaceships and points limit for one spaceship ( 1 <= n <= 10 5 , 1 <= M <= 100 ). In the next line there are three integers 1 <= p A , p B , p C <= M - point values for destroying spaceships of different colours. In the last line there is a string of length n - description of subsequent spaceships. Every character is one of the following: A, B, C. Different characters correspond to different colours. Output For every testcase you should output one integer - highest score you can get. Example Input: 2 7 5 1 1 5 AAACAAA 6 10 1 1 10 ABABAB Output: 20 7 Explanation In the first testcase we destroy all six spaceships of colour A, and we get 1+2+3+4+5+5 = 20 points. If we destroyed all of them instead, we'd get (1+2+3)+5+(1+2+3) = 17 points. In the second testcase we can first destroy all spaceships of colour A, and then the last spaceship of colour B, which will give us (1+2+3)+1 = 7.
34,391
The Chase (CHA) Archibald the Archeologist was dashing forward as fast as he could, clutching The Idol of Ingenuity tightly. Seizing that artifact almost got him killed 1 , but he still wasn't safe - bunch of South American Indians from Kampa tribe was right on his tail. Fortunately none of them had bows, but they will surely kill him as soon as they catch him. Intricately made figurine was shimmering beautifully in the sun, but at that moment it was only slowing him down - Kampas were faster than him in any case. The situation seemed hopeless... ... but it wasn't. This wasn't a typical jungle - the ground was paved with giant stones, and combined with the surrounding impassable rainforest, it all formed something resembling a corridor. This was surely made by the ancient La-Og-Mhtir civilization, just like the idol. The "corridor" was very long, but very regular - every stone looked like a square, and they were adjoined tightly, one next to the other. Moreover, this corridor was mentioned in the records Archibald studied for years - it surely was The Way Towards Enlightenment. He already expected to find it on his way to the idol, but maybe the map was upside-down... ... anyway, this is good news. Way Towards Enlightenment isn't just a typical road - it contained a lot of deadly traps. There were levers hidden on some of the stones - every such lever activated a trapdoor hidden below the previous stone. Archibald knows exactly where every lever is. The situation is as follows - Archibald stands on a plate number a . There are n Kampas chasing him, and i-th Kampa is on the x i -th plate. Every Indian moves onto the next plate every second. Archibald is slower - at the start of every second he can decide to move forward, but he will reach the next plate after two seconds. There are m levers, and their positions are denoted by y i . If Archibald reaches one of those levers, he can immediately activate the trapdoor - if there is a Kampa on the plate number y i -1 at this exact moment, he will fall into a deadly trap. Activating the trap earlier is no good - without the element of surprise, the natives will spot it in advance and run through it safely (probably a bit to the side). The plan is very simple - neutralize all the Indians without getting caught by them. 1 You can find this story in the problem "The Idol" , from PIZZA 2017 qualifying round. Input The first line contains a single integer t , denoting number of testcases. Then, testcases follow. The first line of a testcase contains three integers n , m , a ( 1 <= n <= m <= 1000, 0 <= a <= 10 9 ) - number of Indians, number of traps and Archibald's starting plate. In the next line there are n integers x i - plate numbers with Kampas on them at the start. In the last line there are m numbers y i - plate numbers with levers. It is true that: 0 <= x 1 < x 2 < ... < x n < a 0 < y 1 < y 2 < ... < y m <= 10 9 Output For every testcase you should find a sequence of moves that will let Archibald trap every Indian. The sequence should start with an integer r - number of moves ( 0 <= r <= 16 m ). Then you should give a description of the subsequent r moves. Possible moves are as follows: P x - Archibald goes to the right x times. Every move takes him 2 seconds. S x - Archibald stands still for x seconds. X - Archibald activates a trapdoor (this happens instantaneously). There has to be a lever on the plate Archibald is standing on. You cannot activate the same trap more than once. In every case x is an integer, and x >= 1. Archibald cannot go to the left, because there is no turning back from The Way of Enlightenment. If at the start of a second Archibald will decide to go to the right, he will still be standing on the same plate at the start of the next second - he will appear on the next plate two seconds after his decision. Indians move at the same time as Archibald - at the start of every second the decide to go right, and at the start of the next second they are at the next plate. At no point should any Kampa stand on the same plate as Archibald. Input is constructed in such a way that a correct sequence always exists. Example Input: 1 2 2 8 0 3 12 14 Output: 5 P 4 X P 2 S 1 X Explanation Archibald has to run towards the first lever as fast as he can - after 8 seconds from the start he reaches square number 12, and this is the last possible moment - Kampa closest to him reached plate number 11 already. After he reaches the second trap he has to wait for a second, so the Indian is right above the trapdoor.
34,392
Cyclic Counting Gamble (CCGAMBLE) Nowadays, gamble is so familiar even though it is prohibited in some countries. There are so many ways to gamble. Every rules of gambling always include the probability to win the game. Here, there is a unique rule of a gamble. This rule is called Cyclic Counting Gamble. This game is played by N players and there is only one winner. Those N players are standing and making a big circle. They are numbered from 1 to N. One player is pointed to be number one. Then, player who is in right side of the player numbered i, become player number i+1 (for 1 ≤ i < N). To decide who is the winner, they will chose one number K, then the following algorithm is used: Starting from player number one, saying "one" (1). Then, right side of player who is saying i, will say i+1. Repeat the second rule until a player saying K. That player will be considered to be lose, get out from circle and can't play anymore. Player who is right side of that lose player will say "one" and back to second rule. Repeat that algorithm until one player left, that player become the only winner. Now, N players want to join that gamble (N is given). Then, they already chose K. Because N and K is too large, then the game can't finished although one century. Here, you are to find the fastest algorithm to know the winner in less than 0.5 second. Input Given N and K in one line separated by a white space. Output The only line contain one number represent the winner of that game. Constraint 1 ≤ N, K ≤ 10 18 N ≤ 10 7 or K ≤ 10 5 Example Input: 5 2 Output: 3 Explanation Sequence of players who are saying: 1 say 1 2 say 2 (lose) 3 say 1 4 say 2 (lose) 5 say 1 1 say 2 (lose) 3 say 1 5 say 2 (lose) The winner is player with number 3.
34,393
Cake Walk (CKEWLK) In a country called STI Countries (STI stands for Super Toxicity Inc.), there is one day dedicated for the people to do everything they want. This day is called FREE DAY. Of course they must keep their activities not to violate the law. For example, everything that lead to criminality is forbidden because it violates the law. The president of STI Countries is very excited to FREE DAY . For him, being a president made him as the busiest man in the world, so holiday is almost impossible for him, even Sunday. But, FREE DAY gives him a chance to feel freedom from all of his duty as the president. For this FREE DAY, president and his family want to make a party. This party is called Cake Walk Party. As it namesake, this party will have relation with cakes. So, president needs a talented baker for the best cakes he want. Then, the president called Brembo, the best baker in the country. Called by the president, the baker will make sure the cakes he made would impress the president. The president will order T cakes , with every of them is different type. To make a cake, Brembo needs M package of ingredients. The type of a cake will be represented by a number that is N . After doing some experiments, he finds a good formula to make the ingredients of cake with type N . He called this F(N). He writes the formula F(N) as F(N) = F(1) + F(2) + F(3) + F(4) + ... + F(N-1) with F(1) = M. Normally, the cake with type N, will be priced C(N) in dollars, where C(N) = M + N + F(N). But, because today is a special day plus he is doing job for the president, the way of pricing a cake is different than before. He makes rules as the following : From C(N), find all special factor of C(N). Because Brembo is not good at explaining, Brembo defines special factor of a number with examples. For example 24, the special factors are 2 3 and 3. For 15, special factors are 3 and 5. And so on. Then, the price of the cake will be taken from factor with the highest value. So, from the example above, 24 will be priced 3 instead. So far, 15 will be priced 5 instead. Considering the results of C(N) can be very large, he does C(N) mod 1000000007 for every C(N) he calculates, then factorize it. As the assistant of Brembo, you need to calculate the total cost that president must pay for the T cakes he orders. Because this task will be exhausting, you build a program to make the calculation faster. Input The first line of input consist of two integers, T and M separated by space. T represents the number of cake that The President will order and M represents the package of ingredients. (1 ≤ T ≤ 100 and 1 ≤ M ≤ 1000000) The next T lines each contain one integer N i , representing the type number of cake i. (1 ≤ N i ≤ 1000000) Output Print the total cost that The President must pay using the following format : "The President needs to pay (total) dollar(s)" without quotes. Please, take a look to example. Example Input: 3 11 2 3 4 Output: The President needs to pay 65 dollar(s)
34,394
Smelly Toilets (SMTOILET) There are N toilets around Duck, each of them will begin to release O i units of odors after i units of time. For example, there are three toilets producing 20, 10, 15 units of odors respectively. The first toilet will immediately release smells, the second one will release smells after 1 seconds and the third is after 2 seconds. So at the time 1, the total amount of released odors is 20 * 1 = 20, at time 2 is 20 * 2 + 10 * 1 = 50 and at time 3 is 20 * 3 + 10 * 2 + 15 * 1 =  95. Duck can only go to toilet when the absolute difference between the total amount of released odors at a certain time and his tolerance to odors M is minimized. Please find out at what time the difference is minimized. If there are two answers, choose the larger time. After that, Duck will enter one of the toilets randomly. Given a string S , Duck knows which cubicles are available and which are occupied, 'x' means occupied and 'o' means available. Let the time that minimizes the difference be ANS , and the smallest power of 10 that equal or larger than ANS be P .   Assuming the toilet entrance is located at the position floor(ANS / P * (len(S) - 1)) of S, that is, the cubicle at that position is replaced by the entrance. You are required to select the best cubicle for Duck: available, maximizes the total distance between the nearest occupied cubicle on the left and right side as possible and it should be in the middle between the left nearest and right nearest occupied cuicle as possible (if no occupied cubicles next to the chosen range, you may assume there is an occupied cubicle on the most left and most right side and the entrance is also an occupied cubicle), and then as close to the entrance as possible. If there is more than one best choice, select the one on the right side of the entrance because Duck is always right. Please help him, he wants to excrete comfortably. Input The first line is the number of test cases T . (1 ≤ T ≤ 50) For each test case, it starts with two integers N (Number of toilets) and M (Duck's tolerance to odors). (1 ≤ N ≤ 500, N ≤ M ≤ 10 18 ) The next line is a string S consisting of 'x' and 'o', representing the status of cubicles (3 ≤ |S| ≤ 100) Following N lines are the O i units of odors released by i th toilet (1 ≤ O i  ≤ 10 5 ) It is guaranteed that in S, 'o' will appear at least twice, so the answer always exists. Output Print two integers in format 'x y' without quotes, where x is the time minimizes the absolute difference between the total amount of released odors at a certain time and M, y is the position of best cubicle counting from 0 Example Input: 2 2 4 78 ooxoxxoooxxxxxooooxoooo 2 13 1 5 5 35 xxoooxoooxx 1 2 3 4 5 5 Output: 5 15 5 7 Explanation In case one, the time is 5 because 2 * 5 + 13 * 4 + 1 * 3 + 5 * 2 = 75 minimizes the difference between it and 78. The length of S is 23, so the entrance is at position floor(5 / 10 * 22) = 11, and S becomes 'ooxoxxoooxxExxooooxoooo', and we can see that the cubicle at position 15 is available, as far away from the nearest occupied cubicles as possible, and as close to the entrance as possible. In case two, at time 5, the minimized difference is 0. So S becomes 'xxoooEoooxx'. There are two best cubicles: position 3 and 7, and we choose the right one, so the answer is 7.
34,395
Ludic Numbers (medium) (LUDIC1) Find the number of Ludic numbers less than or equal to $N$. Input The first line contains $T$ ($1 \le T \le 1000$), the number of test cases. Each test case contains a single integer $N$ ($1 \le N \le 10^9$). Output For each test case, output the number of Ludic numbers less than or equal to $N$. Example Input 10 1 2 3 4 5 10 100 1000 1000000 1000000000 Output 1 2 3 3 4 5 24 142 66164 43956562 Note See LUDIC2 for a harder version. Other references for the Ludic numbers: Ludic numbers or A003309 .
34,396
Ludic Numbers (hard) (LUDIC2) Find the number of Ludic numbers less than or equal to $N$. Input The first line contains an integer $N$ ($1 \le N \le 10^{11}$). Output Output the number of Ludic numbers less than or equal to $N$. Example Input: 100000000000 Output: 3603128157 Note See LUDIC1 for an easier version. Other references for the Ludic numbers: Ludic numbers or A003309 .
34,397
Triangle on Binary Tree (TRIBT) You are given a parent array P of length N that represents a binary tree with N nodes, which may be unbalanced, balanced, complete or full. The array indexes are values in tree nodes and the array values represent the parent node of that particular index, a value -1 means that particular index is the root of the tree. This gives both left child and right child or only left child, for a parent, right child cannot exist without left child. You are required to count the total number of potential isosceles triangles in the binary tree. A potential isosceles triangle is the two sides of equal length must be formed by two paths of equal length from a parent or root. Due to the nature of binary tree, not three sides are connected, you can just ignore the remaining unconnected side. Consider a parent array [1, 5, 5, 2, 2, -1, 3], it constructs a binary tree like:  There are 4 potential isosceles triangles in total, they are (1, 5, 2), (0, 5, 4), (3, 2, 4) and (3, 2, 5) respectively. Input The first line is the number of test cases T . (1 ≤ T ≤ 50) For each test case, it starts with one integer representing the number of nodes or length of the array  N . (1 ≤ N ≤ 10 5 ) The next line has N integers, P i is the node's parent node (-1 is the root) and i is its value. (-1 ≤ P i ≤ N - 1) Output Print the total number of potential isosceles triangles. Example Input: 3 7 1 5 5 2 2 -1 3 20 -1 0 0 1 1 3 5 4 7 4 8 8 9 10 10 9 15 15 16 16 5 3 0 1 -1 2 Output: 4 20 0 Explanation Let's visualize the sample input: Case 1 is just the sample mentioned above. Case 2 has 20 potential isosceles triangels: (1, 0, 2), (3, 1, 4), (5, 1, 9), (6, 1, 15), (7, 4, 9), (8, 4, 15), (10, 4, 17), (12, 9, 15), (10, 8, 11), (16, 15, 17), (13, 10, 14), (18, 16, 19), (4, 1, 0), (1, 4, 7), (4, 9, 12), (7, 8, 11), (9, 15, 16), (8, 10, 14), (15, 16, 19) and (4, 15, 18). Case 3 has no triangles.
34,398
Incomplete hierarchy (PODUZECE) After many years of art, young Florian wants to work in a conglomerate. This company consists of N employees denoted 1, 2 ... N, of which some are interns . Florian knows all interns in this company. In the hierarchy, every employee has a single boss, except for one employee (the CEO) who does not have a boss. There is no cycle within the hierarchy; in other words, the hierarchy is a tree. Also, an   intern cannot be superior to a non-intern . Speaking to interns, Florian has collected a wealth of information about parts of the hierarchy. Namely, for every intern he knows who his/her boss is (this boss could also be an intern). Florian now counts the distance of two interns in the hierarchy, which is the number of bosses between these interns. More precisely, the distance in the hierarchy between two employees is obtained by climbing the hierarchy starting with them, and counting all their direct or indirect superiors up to their first common superior (including him). If one of the observed two employees is superior to another (directly or indirectly), we only count the employees who are strictly between them in the hierarchy. Help young Florian determine the largest distance of two interns across the hierarchy, if this number can be uniquely determined from the known data. Input The first line contains two integers N and M, the total number of employees in the company and the number of interns (2 ≤ M < N ≤ 100 000). Each of the following M lines contains two integers A and B, intern and his boss (1 ≤ A, B ≤ N, A ≠ B). No intern will have two bosses. Output Print the required largest intern distance, or -1 if the answer cannot be determined. Example Input: 5 4 2 1 3 2 4 3 5 4 Input: 7 4 1 2 2 3 4 5 5 6 Input: 3 2 2 1 3 1 Output: 2 Output: -1 Output: 1
34,399