task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Farmer Cream (UCV2013C)
Farmer Cream is a businessman that wants to live in the suburbs. He recently bought a little farm in Creamville and wants to earn money from it. After the purchase, Farmer Cream has D money remaining to spend. He's in negotiations with an important firm of farming but he thinks they're not being honest (they're trying to steal some money). He knows the number of fences F in the farm but he doesn't know the number of plots P to farm. The firm is offering a budget B per plot, so he needs to multiply the budget per the number of plots to know the total amount of money to spend. He needs to know if he accepts the contract, for that, he needs to have at least M money to live after the buy. Otherwise, the firm is trying to bankrupt Farmer Cream and take over the farm.
In order to do this. Farmer Cream needs your help. Assuming the fences are lines y = ax + b he only knows three things about them.
There is no point in the farm where 3 or more fences collides. So, in one point of the farm there'll be zero, one or two fences.
There are no parallel fences in the farm. So if we have two fences represented by y1 = a1x1 + b1 and y2 = a2x2 + b2 we assume that a1 <> a2.
All the fences collide with each other
In the example, there are 3 fences and 7 plots.
Input
The input contains several test cases, each one corresponding to a different situation. Each test case consists of a single line with four integers D F B M (1 <= F,B,M <= 10^6) and (1 <= D <= 10^18) separated by a single space. D represents the remaining money of Farmer Cream, F represents the number of fences, B represents the budget in Bsf per plot and M represents the minimum amount of money that Farmer Cream needs to live.
The end of input is indicated by a test case with D = F = B = M = 0.
Output
For each test case, you'll print: "The firm is trying to bankrupt Farmer Cream by X Bsf." where X represents the difference between money to spend plus the money he needs to survive and the money Farmer Cream has. Otherwise, you'll print "Farmer Cream will have Y Bsf to spend." where Y represents the money Farmer Cream will have to spend.
Example
Input:
160 1 70 30
500 3 50 100
250000 40 300 5000
0 0 0 0
Output:
The firm is trying to bankrupt Farmer Cream by 10 Bsf.
Farmer Cream will have 150 Bsf to spend.
The firm is trying to bankrupt Farmer Cream by 1300 Bsf. | 33,300 |
Distributing V-Energy (UCV2013D)
As you probably know there is a new kind of energy called V-energy which is more affordable than electricity, and has some really interesting properties. The Universal Company on V-Energy has just reached your city and is currently planning the location of the distribution centers. You are given a map of the city, the list of the location of the distribution centers, and they need you to report which is the minimum amount of energy that would reach a building of the city, and how many buildings share that amount of energy
V-Energy has the following properties:
If a building has K units of V-Energy it will consume C units and distribute K - C to every building it is connected to. If K < C the building will consume K units and will not distribute any units of energy.
If a building receives V-Energy from different sources it will only consume and distribute the energy with maximum value. For example, if a building receives K = 8 units of energy, and C = 3 it will consume 3 and distribute 5. But, if later the same building receives K = 6 units of energy, it will not consume or distribute this energy since previously it received a larger amount of energy. If later on the same building receives K = 15 units of energy, it will consume 3 units, and distribute 12 units to its neighbors.
As you know, your city is a grid, with buildings on every intersection of the streets. Since V-Energy propagates only through streets, the streets map of the city is perfect for your job. Avenues run horizontally while streets run vertically. Note that sometimes a street or avenue can be blocked. The next figure shows a possible view of a city where street 1 is blocked between avenues 1 and 2, and avenue 2 is blocked between streets 0 and 1.
Input
The input contains several test cases. Each case starts with a line containing the values K and C (amount of V-energy each distribution center has and amount of V-energy each building consumes). (0 <= C,K <= 10000). The next line contains two values N and M denoting the number of avenues and streets on the city (1 <= N,M <= 1000). The following line will have one value B which denotes the number of street and avenues segments that are blocked and cannot distribute V-energy (0 <= B<= N*M-N-M). The following B lines will have four values T I J1 J2. T indicates the type of the segment, can be either 'A' of 'S' to denote an avenue segment or a street segment. I denotes the street or avenue index (0 <=I < N). If it is an avenue segment then J1, J2 are the indexes of the starting street and ending street where the avenue is blocked. If it is a street segment, J1, J2 are the indexes of the starting and ending avenues where the street is blocked (0 <= J1 < J2 <= M). The next line will have the number D of deposits (0 <= D <= min(1000, N*M)). The following D lines will have a pair Ai Si indicating that on the intersection of avenue Ai with street Si there will be a distribution center. (0 <= Ai < N, 0 <= Si < M).
The end of input is indicated by a test case with K = C = 0.
Output
For each test cases you have to print a line containing two numbers Q and P indicating the minimum amount of energy that reaches a building on the city, and the number of building with that amount of energy.
Example
Input:
2 1
2 3
0
2
0 0
0 2
12 2
3 3
2
A 2 0 1
S 1 1 2
1
2 0
0 0
Output:
0 1
2 1 | 33,301 |
Greedy Walking (UCV2013E)
Reginald is an N-dimensional traveler who wants to return to Filipistonia's Kingdom. He has an Obsessive-compulsive disorder in the way he travels so he can only do it following particular rules:
Every step is exactly one unit long.
He only moves in one dimension at a time.
He only travels along the positive direction for each dimension.
For example, when traveling on a two-dimensional place. He can travel along either the X or the Y axis at any given time, but never on both at the same time. Moreover, since he only travels along the positive direction and every step is one unit long, his only possible moves are (+1, 0) and (0, +1).
As you can see, he is a Greedy Walker: once he makes a decision he assumes it is the correct and he never goes back.
Given a starting position in an N-dimensional space (x
1
i, x
2
i ... x
n
i) your task is to count the number of different travels he can make to position (x
1
f, x
2
f ... x
n
f) modulo 1000000007.
Input
The input contains several test cases, each one corresponding to a single travel. Each test case consists of a single line with one integer (1 <= N <= 50) followed by two lines each one with N integers, first line will be initial position and second line will be target position.
You can assume that 0 <= x
k
i <= x
1
f <= 500 for all k, 1 <= k <= N and Sum(x
k
i-x
k
f) <= 500.
The end of input is indicated by a test case with N = 0.
Output
For each travel output a single line with one integer, the number of different travels that exist from the initial position to the final position modulo 1000000007.
Example
Input:
2
2 1
5 5
4
0 0 0 0
1 2 3 4
5
1 2 3 4 5
8 5 6 4 8
5
0 0 0 0 0
100 100 100 100 100
0
Output:
35
12600
19219200
257055440 | 33,302 |
Life on Fornax (UCV2013F)
NASA's Ultrasonic Crawling Vessel, UCV for short, has arrived to galaxy UDFj - 39546284 in the Fornax constellation and has found a peculiar type of bacteria-like lifeform. As you may imagine a plan to collect samples a bring them back to earth has been set in motion. However, it would be rather unfortunate if they are all dead by the time the UCV gets back, the trip would take approximately 13.42 x 10^9 years travelling at light speed. Therefore, its necessary to pick a number of bacterium so that there are at least some of them alive when the UCV arrives back.
The UCV has studied the reproduction cycle of the bacterium inside a cryogenic pod and their behavior when released from the pod, but it lacks the algorithm to compute the final number for such a long period of time. Fortunately, it's been designed with a wormhole plugin installation mechanism that allows to upload algorithms in a matter of only a few years.
Aging phase: Each bacteria becomes a year older.
Reproduction phase: Each bacteria gives birth to a new bacteria, this is slightly different to earth bacteria in the sense that the new and old bacterium are no identical. The new bacteria is 0 years old while the old bacteria is at least 1 year old.
Passing phase: Each bacteria that reaches maturity, exactly M years old, dies.
Fox example, this one reproduction cycle given a 0 years old bacteria and a 1 years old bacteria if maturity is reached at 2 years old.
As you can see, during cryogenic reproduction, there's no fear of bacterium extinction, the number of births is at least as much as the number of deaths. However, when the pod is opened the bacterium enter into a strange iterative reduction phase, in each step of the reduction the oldest R bacterium die immediately; this process ends when there are fewer than R bacterium left. Note that the biggest problem arises when at some iteration there are exactly R bacterium left because they all die at that moment.
NASA ha asked you to write the algorithm that will be uploaded to the UCV to determine the number of bacterium that will exist after the pod is opened here on earth.
Input
The input contains several test cases, each one corresponding to a single simulation. Each test case starts with a line with three integers, the maturity age (1 <= M <= 50), the number of years for the UCV to come back (0 <= Y <= 10^12) and the reduction size (1 <= R <= 10^9); separated by a single space. The following line contains M integers, they
represent the number of 0, 1, ...,M - 1 years old bacterium placed inside the cryogenic pod.
The end of input is indicated by a test case with M = Y = R = 0.
Output
For each simulation output a single line containing a single integer, the number of bacterium that will be alive after the reduction process has finalized.
Example
Input:
2 1 4
1 1
2 1 2
1 1
2 2 2
1 1
2 2 5
1 1
6 0 100000
0 1 2 3 4 5
6 1000000000000 100000
0 1 2 3 4 5
0 0 0
Output:
3
1
1
0
15
21809 | 33,303 |
Schedules (UCV2013G)
PEPE the singer has released a new song. He wants to control how many times his songs is played on RUMBA FM radio station. PEPE has hired two companies (A and B) to perform this task. Every day, they give him a schedule indicating the time when the song has been played on the radio. Song always takes the same number of seconds to play, so end times are not important. We are only interested in start times.
On the first day PEPE received both schedules. They were almost identical. He verified that each entry of A corresponds to exactly one entry in B. He simply took a pencil, and he marked one entry in A, and then the corresponding entry in B. He continued with this approach as long as unmarked entries exist. The second day PEPE again received both schedules, but he found that the number of entries in both schedules is not the same. Moreover, the times did not match at all due to a human error. He said, "Oh Gosh!, I have to reconcile both schedules, finding the best possible match between them". He only trusts the entries that can be matched in both schedules. But how to match them? PEPE started by deciding how many seconds of error (difference) he is able to tolerate for two matched entries. Then he tried to find the largest number of possible matches. For equally large matchings, he is interested in smallest average time difference in seconds. Unfortunately, it may take too long since his new song are very popular, having many hits in RUMBA FM. So, we need your help to perform this task automatically.
Input
The input consists in several test cases. Each test case starts with a line containing three integer numbers Na, Nb, and S, separated by single spaces. Na and Nb are the number of entries in A and B respectively (1 <= Na, Nb <= 200), and S is the tolerance in seconds (0 <= S <= 7200). The second line contains Na time stamps in the format hh:mm:ss separated by single spaces. The third line contains Nb time stamps in same format as the previous one. Note that all start times are in the same day.
The end of the input is an empty test case, where Na = Nb = S = 0 and should not be processed.
Output
For each test case, the output is a single line containing an integer K and floating point number V rounder to one decimal place. K is the largest number of matches between schedule A and schedule B. V is the average time difference in seconds between the K matched entries. In case there is no possible match, your program should instead print "No matches"
Example
Input:
4 2 120
03:00:00 03:00:59 07:40:00 12:40:04
02:59:14 12:41:45
3 2 60
03:00:59 07:40:00 12:40:04
02:59:14 12:41:45
0 0 0
Output:
2 73.5
No matches | 33,304 |
Slick (UCV2013H)
A maritime accident has caused oil to spill onto the seas of Felipistonia, which is a major natural disaster. The Felipistonia's government wants to clean up this mess before more damage occurs. To do this, they first have to know how serious was the accident and the amount of oil that has been spilled into the sea. The only instrument the Felipistonia's government has to get information of the magnitude of this disaster, is the use of satellite images. With these images they can estimate how much money they have to spend to clean this mess. For this, the number of slicks in the seas and the size of each slick must be know. A slick is a patch of oil floating on water. Unfortunately, the Felipistonia's people are not very bright, so they have hired you to help them process the image.
An example of an image obtained by the satellites is shown in Figure 1(a). This image can be transformed to 0's and 1's as seen in Figure 1(b). Given this binary matrix, your job is to count the number of slicks in the ocean and their corresponding size. Two adjacent pixels in the image are considered to be in the same slick if they are in the same row or the same column.
Figure 1: (a) A satellite image of the spilled oil. (b) The representation of the image in a binary
matrix
Input
The input contains several test cases, each one corresponding to a different satellite image. The first line of each case contains two integers that indicate the number of rows (N) and columns (M) in the image (1 ≤ N, M ≤ 250). Then N lines follows with M integers each, containing the information of the image.
The end of input is indicated by a test case with N = M = 0. This case should not be processed.
Output
For each image, output the number of slicks in the sea. Additionally, output the size of each slick in ascending order and the number of slicks of that size.
Example
Input:
10 10
1 1 1 1 1 1 1 1 1 1
1 1 1 1 0 0 0 0 0 0
1 1 1 0 0 0 0 1 1 1
1 1 0 0 1 0 0 1 1 1
1 0 1 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
1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
0 0
Output:
7
1 2
2 1
6 1
10 2
20 1 | 33,305 |
Tambourine (UCV2013I)
Little HH loves tambourines. He loves them so much that now he wants to build them. A tambourine is a musical instrument shown in Figure 1(a). As you can see in Figure 1(b) the tambourine is just a big circle of radius R with N smaller circles of radius r (r < R).
Figure 2: (a) A tambourine. (b) The radius of the circles is shown. (c) There is a 2N sides regular polygon inscribed in the outer circle
HH knows the radius of the small circles (r), he also knows the number of small circles that he has (N). And he knows that the small circles should be centered on the center of the even sides of a 2N sides regular polygon inscribed in the big circle (the sides of this polygon each measuring 2r), as shown on Figure 1(c). Now HH wants you to help him find the radius R of the big circle.
Input
The input contains several test cases. Each test case consists of two values r and N as described previously. (0 < r ≤ 100), (2 ≤ N ≤ 10000).
The end of input is indicated by a test case with r = N = 0.
Output
For each test case you must print a number (rounded up to two decimal places) showing the radius of the big circle to build the tambourine.
Example
Input:
1 4
2 4
1 8
0 0
Output:
2.61
5.23
5.13 | 33,306 |
Valences (UCV2013J)
Mr. White has found a way to maximize the purity of crystals based on certain chemical compounds. He has observed that each compound is made of molecules that are linked together following the structure of a complete binary tree where every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Each node of the tree stores the valence of a molecule and is represented as an integer number. Mr. White uses an electronic microscope that dumps the molecule structure as a stream of integer numbers and would like to have your help on automatically obtaining the total valence of only the leaves of the given tree. For example, the sequence 4-3-2-6-0-3 represents the tree shown in the figure and the total valence of the leaves is 9.
Input
The input contains several test cases, each one corresponding to a particular compound. Each test case consists of a single line starting with an integer N (1 ≤ N ≤ 1000000), followed by N integer numbers Vi representing the valences of each molecule separated by blank spaces (0 ≤ Vi ≤ 100).
The end of input is indicated by a test case with N = 0.
Output
For each compound output a single line with the sum of the valences of the leaves of the tree.
Example
Input:
6 4 3 2 6 0 3
7 1 1 1 2 1 2 1
0
Output:
9
6 | 33,307 |
Zombie Outbreak (UCV2013K)
As many books, movies and video games had shown us, a zombie outbreak was inevitable. However, all hope is not lost. As usual you've encountered a young girl that has been bitten but not transformed. Therefore, you've escorted her to a medial facility so her blood can be studied and a cure manufactured.
Unfortunately, the medical facility, for obvious reasons, has not been resupplied in a while. The scientists there have asked you to pick several tools, viruses and whatnots, from N places in the city.
Now that you have to go out again, you have created a map with the N + 1 locations: the medical facility (location 0) and the other N where the scientists need you to pick something up (numbered from 1 to N). You've also came up with M two-way paths between some of the locations and the probability to encounter a zombie pack on each of those paths. Note that this is isn't science fiction. If you encounter a zombie pack, you will not survive.
You certainly want to fetch all the items and come back alive. You want to compute the maximal probability of picking every item and coming back to the medical facility (safe and sound) if you take a closed walk (cycle that allows node repetitions).
Input
The input contains several test cases. Each test case begins with two integers, the number of places you have to go to (1 <= N <= 16) and the number of paths you came up with (1 <= M <= N^2), separated by a single space.
The next M lines contain 2 integers and a real number separated by spaces. Two integers ui and vi (0 <= ui, vi <= N and ui<>vi) are the locations this path connects. Real number pi (0 <= pi <= 1) represents the probability that you will encounter a zombie pack along this path.
You may assume that, for all i <> j, probabilities pi and pj are independent from each other.
The end of input is indicated by a test case with N = M = 0 and should not be processed
Output
For each test case output a single line with a single real number: the probability of getting back to the medical facility alive with all items. Round the result to exactly three places after decimal point. If there's no way to pick all items, you should output 0.000.
Example
Input:
2 3
0 1 0.3
0 2 0.4
1 2 0.2
2 3
0 1 0.3
0 2 0.5
1 2 0.1
2 2
0 1 0.1
0 1 0.9
2 3
0 1 0.92
0 2 0.92
1 2 0.92
2 3
0 1 0.92
0 2 0.92
1 2 0.93
0 0
Output:
0.336
0.397
0.000
0.001
0.000 | 33,308 |
Yet Another Electronic Device!!! (KCARRY)
Fascinated as he is by the uncanny world of electronics, our friend MKS now decides to launch his own creation → A N-Digit Carry Finder (an analogue of a N-Bit Binary Adder) which can be used to find the number of times we can have a non-zero carry while adding two numbers (A = A
n
A
n-1
... A
2
A
1
and B = B
n
B
n-1
... B
2
B
1
) having
exactly N
digits.
It consists of 'N' Full Decimal Adders. The i-th Full Adder takes as input three digits A
i
, B
i
and C
i-1
and outputs a digit C
i
(0 or 1), which is the carry generated on adding the digits A
i
and B
i
and C
i-1
. (C
i
= 1 if A
i
+ B
i
+C
i-1
> 9, otherwise 0).
This C
i
is now provided to the next (i+1-th) Full Adder in order to be added with the digits A
i+1
and B
i+1
and also to the accumulator which as the name suggests accumulates the sum of all C
j
(1 <= j <= i).
Note
: C
0
= 0 always and 0 <= A
i
, B
i
<= 9.
For Example: Adding two numbers, A = 4567 and B = 734 (or B = 0734), the addition proceeds as shown and the accumulator gets a final value of 3.
In the 1st Adder, A
1
= 7, B
1
= 4, C
0
= 0 and A
1
+ B
1
+ C
0
= 11. Therefore Carry C
1
= 1.
In the 2nd Adder, A
2
= 6, B
2
= 3, C
1
= 1 and A
2
+ B
2
+ C
1
= 10. Therefore Carry C
2
= 1.
In the 3rd Adder, A
3
= 5, B
3
= 7, C
2
= 1 and A
3
+ B
3
+ C
2
= 13. Therefore Carry C
3
= 1.
In the 4th Adder, A
4
= 7, B
4
= 0, C
3
= 1 and A
4
+ B
4
+ C
3
= 8. Therefore Carry C
4
= 0.
The Value in the Accumulator = C
1
+ C
2
+ C
3
+ C
4
= 3.
Your task is to find the number of ways of getting a value
K
in the
accumulator
while adding two numbers containing
at most N
digits each. Note that we are adding the numbers in their
base 10
representation. Since the total number of ways can be very large, print your answer modulo 1000000007 (10^9 +7).
Input
The first line of input contains an integer T. Then T lines follow containing two space separated integers N and K.
Output
Print the required answer modulo 1000000007(10^9 +7) in the i
th
line corresponding to the i
th
Test case .
Constraints
1 <= T <= 500
1 <= N <= 1000
1 <= K <= N
Example
Input:
4
1 1
2 1
2 2
3 3
Output:
45
4500
2475
136125
Explanation
For test case 1, the carry appears when adding:
1 and 9, 2 and 9, 3 and 9 ... 9 and 9 = 9 cases.
2 and 8, 3 and 8, 4 and 8 ... 9 and 8 = 8 cases.
3 and 7, 4 and 7, 5 and 7 ... 9 and 7 = 7 cases.
...
9 and 1 = 1 case.
There are (9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0) = 45 cases in total and in each case, the carry appears exactly once. | 33,309 |
How to Handle the Fans (AKVQLD03)
Trey Parker and Matt Stone, the creators of “South Park” are having some problems handling their fans. The number of fans is so huge that can’t even count them properly. So they hired “N” employees for counting the fans. All the “N” employees had their own separate offices and they were located in a straight line with positions numbered as 1, 2, 3 … up to N. Fans can come to the office of any employee at any time and tell them how they feel about the show and if they are lucky enough, they may get to meet Trey Parker and Matt Stone.
All the employees keep on updating Trey and Matt about the number of fans currently in their offices, so at each moment, they will have a list of “N” positions and the number of fans in each of these positions. Trey and Matt suddenly start taking a walk from office at position “A” to position “B” to meet their fans, but before they start walking they want to know the sum of all the fans in the offices from position “A” to “B”. But counting them one by one is taking a lot of time, so now they hired you, an awesome software engineer to do this task. Your task is to find the sum of all the fans present in the offices between positions “A” to “B” ("A" and "B" inclusive). Let’s see if you could do it fast enough.
Input
The first line of Input contains two integers “N” and “Q”. “N” is the number of employees hired by Trey and Matt. “Q” is the number of queries to be followed.
Each of the next “Q” lines contain a query. A query can be of two types:
“add P F” – this means that “F” number of fans came to the office at Position “P”
“find A B” – this means that Trey and Matt wants to know the sum of fans present at offices at positions “A” to “B”
Output
For each query of the type “find A B”, output the sum of fans present at offices at positions “A” to “B” in a different line.
Constraints
1 <= N <= 10^6
1 <= Q <= 10^5
1 <= A < B <= N
1 <= P <=N
1 <= F <= 10^4
Example
Input:
10 10
find 1 5
add 5 8
add 6 2
find 4 5
find 4 6
add 2 4
find 2 6
add 6 7
find 1 6
find 7 10
Output:
0
8
10
14
21
0 | 33,310 |
Selling Art (SELLINGA)
To the best of her friends’ knowledge, Irina is a great artist. That is why she decided to expose her work and conquer the world. Well, just sell it alright. To help her, her friends executed a decent strategy. For a whole month they went to “The Manége”, an arts exhibition hall in Saint Petersburg. They wrote down on a piece of paper the times at which collectionists enter and leave. Then they consolidated the data and realized that the times at which collectionists enter and leave is the same for every day. For example, collectionist A enters at time
eA
and leaves at time
lA
every day from Sunday to Saturday.
To maximize exposure on any given day, she should arrive at the time the first collectionist enters and leave when the last to leave collectionist leaves, of course. This is impossible because she works every day and her boss won’t allow a day off. She can take several short breaks, fortunately.
Her friends told her that as soon as she enters the Manége at a time
t
, all the collectionists currently present will see her work. Because of this, she realizes she can take
k
breaks. So, she can take a break, enter at a time
t
and go back to work and this will guarantee her that all currently present collectionists will take a look at her work.
She’s quite an artist but unfortunately not good with numbers. Knowing the times at which each collectionist enters and leaves the exhibition hall, she wants to know the minimum number of breaks
k
she needs to take in order to guarantee exposure to all collectionists. Help her. Write an awesome program for her.
Note: actually, this problem is from a parallel universe so times are not the same as in ours. In this universe, the first second of a day is 0 and the last second of a day is 399,999.
Input
The first line of input contains N (1 ≤ N ≤ 2 × 10
5
), the number of collectionists attending the Manége on this day. Then follow N lines. The i-th line contains two space-separated positive integers (si, fi) (0 ≤ si < fi ≤ 399 999), the seconds at which the i-th collectionist enters and leaves, respectively.
Output
First print
k
, the minimum number of breaks Irina needs to take, on a single line. Then print
k
lines. On the i-th line print the time at which Irina needs to show up for the i-th break.
If there are several answers, print the one with earliest break times, in order.
Sample Cases
Input:
3
0 5
1 4
2 6
Output:
1
2
Input:
3
0 1
2 3
4 5
Output:
3
0
2
4
In the first sample case, three collectionists are present. The first collectionist arrives at second 0 and leaves at second 5. The second collectionist arrives at second 1 and leaves at second 4. The third collectionist arrives at second 2 and leaves at second 6. Irina can choose to arrive at seconds 2, 3, 4 and be guaranteed to have all three collectionists see her work. However, she chooses to arrive at second 2 because it is the earliest time.
In the second sample case, she must take 3 breaks: no more than one collectionist is present at any given time. | 33,311 |
Kawigi quote (KIMO4)
Thursday 25/7/2013, a friend of mine (
Goodname
) posted in our facebook group (Virtual Contests) a link of
Kawigi
's topcoder profile.
He was amazed by Kawigi's quote as he tested it in
Ideone
to find it printing "C++Sucks". We all were amazed by this quote.
But in a few minutes some other friend of mine (
Mosa
) commented on the post with this
Ideone
. Wow! he got it, but the fact that he is kind of greedy, he didn't want to tell us the secret. Now we want to think like Mosa to be able to solve this problem.
Given a string your task is to find the values of m[0] and m[1] so that when we run this code we get the given string.
Code
#include <stdio.h>
int primes [] = {2, 3, 5, 7, 11};
double m[2] = {8242465576917890.0, 494};
int main() {
m[1]--?m[0]/=primes[((int)m[1]+1)%5],main():printf((char*)m);
}
// this code prints the string "123".
Input
The first line of the input file contains an integer T (T <= 50) which is the number of test cases to follow.
Each test case will be on a single line consisting of at most 6 alphanumeric characters (A-Za-z0-9).
Output
For each test case, print the values of m[0] and m[1], separated by a space.
It's guaranteed that the solution will always exist. If there are multiple solutions, print any.
Example
Input:
4
123
abdou
mcMosa
kimo3
Output:
8242465576917890.0 494
6966198460426549.0 487
4484456159639948.0 483
21357815651012032.0 488
Special Thanks:
-
Mitch Schwartz
for discovering issues with the problem.
-
Mosa Osama
for writing the special judge of the problem, and I have to say Mosa's not greedy. ;) | 33,312 |
Helping Igor (IGOR)
Dr Samuel has been working in one of his grim (and useless) experiments in order to take control of the humanity.
Recently, he has been working in a hypnotic bomb, and he plans to launch it in the center of the city. Once it falls, all the inhabitants will be under his control, due to the properties of its principal element, the Samuelanium.
Amusingly, the Doctor himself created this element, and he does not know its behavior! He has commanded Igor, his faithful sidekick (and slave) to describe it.
Samuelanium’s behavior is pretty strange. According to Igor’s Notes:
-Its atoms are only composed by electrons and protons and it has a chain-like shape.
-On its sides there are two strange portals. They can suck the proton-electron chain in only one direction. Once a particle enters in a portal, it comes back from the other portal with its charge changed.
-If the first particle in the chain is a proton, the charge of the last particle changes.
For example, suppose we have the chain "+-+".
As you can see, the first particle is a proton, so the last particle must change its charge, becoming "+--". Then, the chain is sucked by the left portal. The proton comes out from the right portal, having changed it charge, becoming "---"(as an electron). This occurs in one second.
So, if the chain is represented as "+-+" at time 0, it will be represented as "---" at time 1.
Doctor Samuel wants to know the state of this chain, having passed some seconds from its initial state.
Unfortunately, Igor is exhausted. Can you help Igor and (ironically) help Doctor Samuel to control the humanity and conquer the whole world?
Input
Your program will be tested with t experiments.
Every experiment begins with two integers, n and k. n represents the length of the Samuelanium chain, and k represents the number of queries that Samuel demands.
Next, there will be a string of length n, composed only of '+' and '-'. '+' represents a proton, and '-' an electron. This chain represents its initial state (time 0).
You must assume that the portal that sucks the chain is on the left side.
Then, there will be k lines, with an integer ki, representing the time query you have been asked for.
Output
For each test case you must print one line containing "Experiment #i:", being i the ith case you are analyzing.
Then, k strings, representing the chain in a given moment.
Remember, protons are represented with '+' and electrons with '-', and there are no neutrons.
Example
Input:
1
3 4
+-+
0
1
2
4
Output:
Experiment #1:
+-+
---
--+
+++
Constraints
1<=t<=15
1<=n<=14
10<=k<=1000
0<=ki<=10^9 | 33,313 |
Simplified Hangul (SHANGUL)
Bob is an American boy and a huge fan of K-Pop ("
Korean-Popular
"), a popular music genre in South Korea. The songs are usually performed by boybands and girlbands, and they usually dance pre-determined choreographies and sing pre-determined lyrics.
Bob already learned some choreographies, but he can't understand the lyrics very well. That's why he is studying the Korean language, in particular the Korean alphabet, Hangul. Bob has some images containing lyrics written in Korean, and needs to know how these texts would sound for an English speaker. Help him by creating a program that reads a image containing Korean text and outputs how it sounds.
In this problem, we'll consider a
very simplified version
of Hangul. There are only 7 letters in this alphabet. Their drawing and sounds are given below:
To form a word, the letters are written in sequence, from left to right. The word's sound is the concatenation of its letters' sound, in order. So, according to the given table, the word
, for instance, sounds like "gangnan".
It's also possible to replace a letter in a word by two letters, one on the top of another, forming a block. The sound of a block is the concatenation of the sound of the top letter and the bottom letter. So, for instance, the block
sounds like "ua", and the word
sounds like "uaneoi".
You are given a matrix that represents a black-and-white image containing a single word. The white pixels represent the background of the image, while the black ones indicate the word itself. Find out how the word would sound like.
(PS: The problem setter is not a Korean speaker. Sorry for possible mistakes.)
Input
The first line of each test case contains two integers
n
and
m
(5 ≤
n
≤ 40, 7 ≤
m
≤ 520), the number of rows and columns of the image. The next
n
lines contain
m
characters each, and represent the image. The character
'.'
indicates a white pixel, while the character '
#
' represents a black pixel.
Restrictions:
The first and last rows and columns of the image will always be blank;
There will be at least one letter in the image;
All letters in the image will be valid;
The length of each
stroke
may vary, but its width will always be 1 pixel;
The length of all vertical strokes in "
a
" and "
eo
" will always be odd, and the horizontal stroke will always intersect the vertical one on its midpoint;
The length of all horizontal strokes in "
o
" and "
u
" will always be odd, and the vertical stroke will always intersect the horizontal one on its midpoint;
The sequence of letters/blocks that form the word will be separated by at least one blank column;
There won't be any letter bellow another letter, except when a block is formed. This indicates that the word was written without linebreaks;
In a block, the bottom edge of the top letter and the top edge of the bottom letter will be separated by white pixels;
In a block, the leftmost pixel of both letters will be in the same column;
The letters/blocks that form the word may not be horizontally aligned;
The blocks and words may not make sense in (real) Korean.
The last test case is followed by a single line containing two zeros.
Output
For each test case, print a string indicating how the given word sounds.
Example
Input:
5 29
.............................
.###.#..#...###.#....#...#...
...#.##.#.....#.#....##..#...
...#.#..###...#.###..#...###.
.............................
19 38
......................................
..#...................................
..#...................................
..#................#..................
..###########......#..................
..#................#..................
..#................#..................
..#................#..................
...................#..................
...................#..................
..#................#..................
..#...................................
..#......................#............
..#......................#............
..#......................#............
..####...................#............
.........................#............
...................#############......
......................................
16 34
..................................
................................#.
....#######.....................#.
.......#........................#.
.......#...............##########.
.......#........................#.
.......#........................#.
.......#........................#.
.......#..........................
..................................
....#...........#.................
....#...........#......#..........
....#####.......#......#..........
....#...........#####..#..........
....#..................#..........
..................................
0 0
Output:
gangnan
anio
uaneoi | 33,314 |
Do You Even Lift (DYEL)
Summer's coming up in a few months, so you decide to hit the gym to put on some muscle. When you arrive, you're confronted with dozens of machines, free weights, barbells, stationary bikes and more. All of this is quite confusing to a newcomer, so you just stand there confused, checking your cellphone a few times, and leave.
After this less-than-stellar experience, you decide to do some research online. You learn that people train in things called "programs", which are instructions to determine how much weight to lift on a particular day. These are always of the form "Lift twice what you lifted three days ago, plus three times what you lifted 7 days ago", or similar. In general, such a "program" tells you that the weight you need to lift today is some combination of the weights you've lifted previously. The program also gives you some initial weights, for when the formula doesn't make sense.
Being very clever, however, you decide that the advice you find during your research is for suckers. You won't even bother with known programs like Starting Strength, StrongLifts 5x5, or even CrossFit. What you'll do is much cleverer: You'll go to the gym, find the most jacked bro in there, and imitate his program. To figure out his program, you'll record what he lifts each day he goes to the gym, for a few days.
Since you are lazy, of all the possible programs he could be following which would match your observations, you want only the shortest one (the one that mentions as few days back as possible). Can you find it?
Input
The input consists of multiple test cases, and starts with a positive integer T. T test cases follow.
Each test case starts with a number K, the number of days you've watched the bro lift weights for. After that come K nonnegative integers W_i, denoting the weight he lifted each day, from oldest lifts to most recent ones. You are assured that the bro is indeed following a program.
Output
For each test case, output a single line, consisting of N space separated non-negative integers D_i, if the program says each day you should lift the sum of (D_i times the weight you lifted i days ago), for 1 ≤ i ≤ N. N is the length of the shortest solution you found and should not be printed
Example
Input:
5
10 48 64 96 128 192 256 384 512 768 1024
8 3 3 2 25 136 782 4479 25659
8 3 3 24 87 381 1578 6639 27807
14 3 3 1 2 4 8 16 32 64 128 256 512 1024 2048
8 16909 42737 110373 281321 722813 1848097 4739349 12131737
Output:
0 2
5 4 1
3 5
2 0 0
1 4
Constraints
1 ≤ T ≤ 5 * 10^3
1 ≤ K ≤ 44
K = 0 (mod 2)
0 ≤ W_i < 2^63
In every program, K ≥ 2N.
Warning: You may need to use very big integers. | 33,315 |
Hamsters (STC00)
Byteasar breeds hamsters. Each hamster has a unique name, consisting of lower case letters of the English alphabet. The hamsters have a vast and comfortable cage. Byteasar intends to place a display under the cage to visualize the names of his hamsters. This display is simply a sequence of letters, each of which can be either lit or not independently. Only one name will be displayed simultaneously. The lit letters forming the name have to stand next to each other, i.e., form a contiguous subsequence.
Byteasar wants to be able to display the names of the hamsters on at least M different positions. However, he allows displaying the same name on multiple different positions, and does not require to be able to display each and every hamster's name. Note that the occurrences of the names on the display can overlap. You can assume that no hamster's name occurs (as a contiguous fragment) in any other hamster's name. Bytesar asks your help in determining the minimum number of letters the display has to have.
In other words, you are to determine the minimum length of a string (consisting of non-capital letters of the English alphabet) that has at least M total occurrences of the hamsters' names (counting multiplicities). (We say that a string S occurs in the string T if S forms a contiguous fragment of T.)
Input
The first line of the standard input holds two integers N and M (1<=N<=200, 1<=M<=10
9
), separated by a single space, that denote the number of Byteasar's hamsters and the minimum number of occurrences of the hamsters' names on the display. Each of the following N lines contains a non-empty string of non-capital letters of the English alphabet that is the hamster's name. The total length of all names does not exceed 10
5
letters.
Output
The first and only line of the standard output should hold a single integer - the minimum number of letters the display has to have.
Example
For the input data:
4 5
monika
tomek
szymon
bernard
the correct result is:
23
The shortest display could be, for example:
szymonikatomekszymonika
. It has 5 occurrences of the hamsters' names in total:
szymon
and
monika
occur twice each,
tomek
just once, and
bernard
does not occur in it at all. | 33,316 |
Niceness of the string (IITKWPCA)
The niceness of a string s (s comprises of a-z, A-Z and space characters only) is calculated using steps given below.
First separate out the string into continuous non zero length string without space. eg. Let us take s = "now do it now". You can break this into four small strings as "now", "do", "it" and "now". Call the set of these small strings to be G.
Now reverse all the strings in G. eg. "won", "od", "ti", "won".
Finally you calculate number of distinct strings in you set. in this case answer is 3. as "won", "od" and "ti" are set of distinct strings. Note that "won" comes twice but counted only once.
So you have to find niceness value of a string s.
Note that given string s can contain more than one continuous spaces. eg. "now do it now ". Niceness value of this is also same as above given example.
Input
T: number of test cases. (T ≤ 100)
for next T lines, every line contains one string s (1 ≤ |s| ≤ 10
4
)
Output
For every test case, output niceness value of given string s.
Example
Input:
4
now do it now
now do it now
I am good boy
am am
Output:
3
3
4
1 | 33,317 |
Check the coprimeness (IITKWPCB)
Find largest non-negative number less than or equal to floor (N/2) which is coprime to N.
Two number a and b are considered to coprime if gcd(a, b) = 1.
Input
T : number of test cases (T ≤ 1000).
For next T lines, every line contains n (1 ≤ n ≤ 10
12
).
Output
For each test case, output the answer as described in the problem statement.
Example
Input:
4
3
4
5
100
Output:
1
1
2
49 | 33,318 |
Count right angle triangles (IITKWPCC)
You are given n points in a 2D plane. You are asked these an inherently simple questions about them.
You have to find out number of right angle triangles (having base and height parallel to axis) with the property that length of base and height is same.
Input
First Line will n: number of points. (n <= 10^5).
For next n lines each line will contain two integers x and y. (-10^8 <= x, y <= 10^8).
Output
You have to output a single line containing the answer to question.
Example
Input:
5
0 0
1 0
2 0
0 1
0 2
Output:
2 | 33,319 |
Partition the sticks (IITKWPCD)
You are given a set of N sticks and are required to partition them into groups of exactly 3 sticks each. While doing so, you can leave out any number of sticks out of these groups (in particular, no groups may be formed). One condition needs to be met: sticks in each group need to form a triangle. A triangle can be constructed if sum of any two sticks lengths is greater than the third length.
Your are required to partition the sticks so that the sum of triangle areas from all the groups is maximized.
Input
Very first line of the input contains integer T: number of test cases (1 <= T <= 5).
For each test case, first line contains integer N: number of sticks. (1 <= N <= 15).
Second line contains N space separated integers: the lengths l
i
of the sticks. (1 <= l
i
<= 10^3, 1 <= i <= N).
Output
For each test case, output the maximal area in a separate line. Round value to exactly 6 decimal places.
Always
print exactly 6 decimal places.
Example
Input:
3
3
7 8 5
4
7 8 6 3
3
7 2 1
Output:
17.320508
20.333163
0.000000 | 33,320 |
Let us play with strings (IITKWPCE)
Feluda likes palindromes very much. He is so fond of palindromes that if you give him any string, he will try to break it into continuous palindromes.
As Feluda is a smart boy, he will do try to break the string into minimum number of such continuous palindromes. You have to help Prabhu. Find out the answer for the problem if he is given a string s.
Input
T : number of test cases (T <= 100)
next T lines contain a string s (length of s <= 2000)
Output
For every test case print one line having answer as given in the problem statement.
Example
Input:
4
abacdc
ababa
ababbacababbad
abcd
Output:
2
1
5
4 | 33,321 |
Help Feluda with mathematical equations (IITKWPCF)
Feluda likes numbers very much but hates prime numbers too much. For a fixed n, you gave Feluda equation x
2
+ y
2
+ n = (x + y)
2
. Now you only want positive integral solution of x and y. Feluda being an intelligent person gave you all the pairs of (x, y) but he missed the pairs which had x as a prime number.
For all the solution that Feluda gave you, we want you to just print those values in the following format: first print the number of such x's, then the possible values x sorted in increasing order in a line separated by single space. If no such numbers exist, then print a 0 in the line.
Input
T: number of test cases (T ≤ 100). The next T lines each line contain n (n ≤ 10
12
)
Output
For every test case print as stated in the problem statement.
Example
Input:
3
4
24
100
Output:
1 1
4 1 4 6 12
4 1 10 25 50 | 33,322 |
Help the old King (IITKWPCG)
Once upon a time there lived a king in a far far country. In the country, there are n cities and m roads. He was severely attacked by his enemy. The enemy damaged all the cities of King's country. As the roads between the cities had been damaged, the King wanted to repair those. So he decided to launch a tender for this.
As King's country is a well managed country. By well managed country, we mean that it is possible to go from each city to any other city. But now as the city has been destroyed by enemies, all the roads are broken, the king will like to rebuild the roads in such a way that it is still a well managed country.
Cost of repairing the road in the country is really weird, it is not addition of costs but it is instead multiplication of those. What it means that if the king decides that he should repair 5 roads, then total cost of repairing those roads will be multiplication of all the 5 costs.
As the King's treasure has been damaged by the attack of foreign city, he would like to spend minimum amount of money and that the will want that his country still remains well managed country. Surprisingly the company that was given tender had a rule that all the costs will be in powers of two, as they were really love with binary numbers.
As value of the total cost can be really large. We do not want to know the actual cost, instead output number of divisors of the number.
Input
T: number of test cases (T ≤ 5)
n and m (n ≤ 10
5
, m ≤ 2 × 10
5
)
Next m lines will have a, b, c, which denotes that cities a and b are connected with road of cost c.
(2 ≤ c ≤ 10
18
, and c will always be power of 2) (1 ≤ a ≤ n) (1 ≤ b ≤ n)
Output
For each test case, output a single line containing a number as stated in the problem.
Example
Input:
4
2 1
1 2 16
3 2
2 3 32
1 2 16
3 3
2 3 32
1 2 16
1 3 64
5 5
1 2 2
2 3 2
1 3 4
3 4 16
3 5 8
Output:
5
10
10
10 | 33,323 |
Find Number Of Pair of Friends (IITKWPCH)
You are given n numbers. Any two number are called friends if they have some digit common. eg. (11, 12) and (15, 4561) are friends but (33, 556) are not.
Find out the number of pairs which are friends.
(Formally speaking let us suppose the n numbers are stored in array a[]. You have to find out number of i and j pairs such that i < j and a[i] and a[j] are friends.)
Input
T : number of test cases (1 ≤ T ≤ 7)
For each test case, you will be given two lines, first line will contain n <= 10
6
, then the next line will contain n integers representing a[i] (1 ≤ a[i] ≤ 10
18
.)
Output
For every test case print a line containing number of such pairs as mentioned in the problem statement.
Example
Input:
4
2
12 13
3
10 12 24
3
5 6 7
4
10 11 211 3
Output:
1
2
0
3 | 33,324 |
Find Lexicographically Smallest Permutation (IITKWPCI)
You are given n numbers a1, a2, ... an. You have to permute the numbers in such a way that resulting permutation should be lexicographically smallest . But there is a problem, you can not swap every pair of numbers. You can only swap the position i and j if they are good position. You will be given m pairs of i and j's which will denote good positions.
So complying to restrictions posed here, find the lexicographically smallest permutation of a1, a2 ... an.
Definition: (a1, a2 ... an) is lexicographically smaller than (b1, b2 ... bn) if first index i where ai and bi differs, ai < bi satisfies.
eg. (1, 2, 3, 4) is smaller than (2, 1, 3, 4)
Input
T : number of test cases (T <= 10)
Next Line will contain n and m. (1 <= n <= 10^3 and 0 <= m <= min (n * (n - 1) / 2, 10^5).
Next Line will contains a1, a2, ... an. (a[i] >= 1 && a[i] <=10^6)
For next m lines, each line will contain i, j separated by space which will denote that you can swap ai and aj.
Output
For each test case, output n numbers representing the permutation of a1, a2 ... an according to problem statement.
Example
Input:
2
3 1
3 2 1
2 3
4 2
2 4 3 1
1 3
3 4
Output:
3 1 2
1 4 2 3 | 33,325 |
Check the string Powers (IITKWPCJ)
Feluda likes strings and mathematics very much. As Feluda is still a child, he was only recently introduced to concept of powers. Being a novice guy, he thinks about powering strings as well as numbers. He defines A^n (A powered to n) to be A + A + ... + A which is a concatenation of n copies of A. For example "bhupkas"^2 = "bhupkasbhupkas".
He wants to check if given two strings A and B, can he find such positive integers n and m so that A ^ n = B ^ m. We are only interested in YES/NO answer, no need to give n and m values.
Input
First line contains integer T: number of test cases (T <= 100).
Single line per test case containing strings A and B. Both will be non-empty, of lengths of at most 10^5, composed only of lower case letters.
Output
For each test case, output "YES" if it possible to find integers n and m so that A ^ n = B ^ m or "NO" otherwise (quotes for clarity).
Example
Input:
3
a a
ab ba
praveen praveen
Output:
YES
NO
YES | 33,326 |
Find Distances In A Plane (IITKWPCL)
Feluda loves reading city maps a lot. Now he has got a map of a city where each house is denoted with its x and y coordinate. As he is interested in estimating how good is arrangement of city, he asks you these two questions.
What is minimum distance between any two houses?
What is maximum distance between any two houses?
Now given n points in a plane, you have to answer these two questions? As Feluda is scared by precision of decimal number representation in computers, you should tell Feluda the square of these distances.
Input
First line will contain n : number of houses. (2 ≤ n ≤ 10
5
)
Then next n lines where each line will contain x and y coordinate of house separated by a single space. (-10
9
≤ x, y ≤ 10
9
).
Output
Output one line containing squares of minimum and maximum distance respectively separated by single space.
Example
Input:
10
0 0
5 1
9 2
12 3
14 4
15 5
16 7
17 10
18 14
19 19
Output:
2 722 | 33,327 |
Coprime Again (IITKWPCM)
As You had known up to now that Feluda is very good in mathematics, Now he decided to understand the properties of coprime numbers. Two numbers are called coprime if greatest common divisor of those numbers is 1. One day Feluda was reading mysterious book in which he found this problem.
For a given positive integer n, Find out product of all the numbers from 1 to n excluding those which are not coprime to n. As this product can grow very large and Feluda being a small child gets scared from large numbers. Hence he wants that you should output the product modulo n.
Help little Feluda to solve this problem.
Input
T : number of test cases. (1 ≤ T ≤ 10
4
)
For next T lines, you are given an integer n such that 1 ≤ n ≤ 10
18
.
Output
For each test case, output one line as stated in the problem statement.
Example
Input:
2
2
5
Output:
1
4
For those who are getting TLE and want to solve easier version. Please go to
IITKWPCQ | 33,328 |
Playing With Balls (IITKWPCN)
There are W white balls and B black balls in a bag. A magician is performing tricks by drawing balls from the bag.
In each step, the magician randomly removes any two balls from the bag. If the drawn balls are of the same color, he will put one white ball in the bag, otherwise he will put a black ball in it. The two drawn balls from the bag from the ball are discarded.
He keeps on doing the above tricks until there is only one ball remaining in the bag.
Given W and B, you have to determine the probability that the color of last ball remaining in the bag is black. You should print the answer with accuracy of up to 6 decimal digits.
Input
T : number of test cases (1 ≤ T ≤ 10
4
)
For every test case W and B are given (0 ≤ W ≤ 10
8
and 0 ≤ B ≤ 10
8
and W + B ≠ 0)
Output
For each test case, output the probability as stated in the problem statement.
Example
Input:
2
1 1
1 2
Output:
1.000000
0.000000 | 33,329 |
Fire Extinguishers (STC01)
Byteasar has had a new palace built. It consists of N chambers and N-1 corridors connecting them. Each corridor connects exactly two chambers. The rooms are numbered from 1 to N. There is only a single entrance to the palace, which leads to chamber no. 1. For each chamber there is exactly one route leading to it from the entrance, without turning back on the way. In other words, the chambers and the corridors form a
tree
- a connected acyclic graph.
The fire marshal who is to approve the building demands placing fire extinguishers inside. The following are his exact requirements:
The fire extinguishers should be placed in (some) chambers, and one chamber may store any number of extinguishers.
Each chamber has to be assigned one fire extinguisher, though it may be stored in another chamber.
Each fire extinguisher can be assigned to at most S different chambers.
For each room its assigned extinguisher is within the range of K corridors.
Byteasar has a week spot for lavish palaces, so it is no surprise he has very little money now, right after completion of another splendid palace. Therefore he is interested in the minimum number of fire extinguishers sufficient for satisfying fire marshal's demands.
Input
The first line of the standard input contains three integers N, S and K separated by single spaces, 1 <= N <= 100000, 1 <= S <= N, 1 <= K <= 20. Each of the following N-1 lines holds two integers separated by a single space. Line no. i+1 contains the numbers X
i
Y
i
denoting the corridor connecting chambers no. X
i
and Y
i
.
Output
The first and only line of the standard output is to hold one integer - the minimum number of fire extinguishers that have to be installed in palace.
Example
For the input data:
12 3 1
1 12
3 8
7 8
8 9
2 12
10 12
9 12
4 8
5 8
8 11
6 8
the correct result is:
4 | 33,330 |
Antisymmetry (STC02)
Byteasar studies certain strings of zeroes and ones. Let S be such a string. By S
r
we will denote the reversed (i.e., "read backwards") string S, and by S
I
we will denote the string obtained from S by changing all the zeroes to ones and ones to zeroes.
Byteasar is interested in
antisymmetry
, while all things symmetric bore him. Antisymmetry however is not a mere lack of symmetry. We will say that a (nonempty) string S is
antisymmetric
if, for every position i in S, the i-th last character is different than the i-th (first) character. In particular, a string S consisting of zeroes and ones is antisymmetric if and only if S = S
Ir
. For example, the strings
00001111
and
010101
are antisymmetric, while
1001
is not.
In a given string consisting of zeroes and ones we would like to determine the number of contiguous nonempty antisymmetric fragments. Different fragments corresponding to the same substrings should be counted multiple times.
Input
The first line of the standard input contains an integer N (1 ≤ N ≤ 500000) that denotes the length of the string. The second line gives a string of 0 and/or 1 of length N. There are no spaces in the string.
Output
The first and only line of the standard output should contain a single integer, namely the number of contiguous (non empty) fragments of the given string that are antisymmetric.
Example
Input:
8
11001011
Output:
7
Antisymmetric fragments are:
01
(occurs twice),
10
(also twice),
0101
,
1100
, and
001011
. | 33,331 |
Difference (STC04)
A word consisting of N lower-case letters of the English alphabet ('
a
'-'
z
') is given. We would like to choose a non-empty contiguous (i.e. one-piece) fragment of the word so as to maximise the difference in the number of occurrences of the most and the least frequent letter in the fragment. We are assuming that the least frequent letter has to occur at least once in the resulting fragment. In particular, should the fragment contain occurrences of only one letter, then the most and the least frequent letter in it coincide.
Input
The first line of the standard input holds one integer N (1 ≤ N ≤ 10
6
) that denotes the length of the word. The second line holds a word consisting of N lower-case letters of the English alphabet.
Output
The first and only line of the standard output is to hold a single integer, equal to the maximum difference in the number of occurrences of the most and the least frequent letter that is attained in some non-empty contiguous fragment of the input word.
Example
Input:
10
aabbaaabab
Output:
3
Explanation of the example:
The fragment that attains the difference of 3 in the number of occurrences of
a
and
b
is
aaaba
. | 33,332 |
Garden (STC05)
Byteen, Byteasar's wife, simply loves flowers. She has decided to have a garden near their house. Byteen is a perfectionist: she would like her garden to be square with sides parallel to North-South and East-West directions. Moreover, Byteen wants each corner of the garden to contain one of the N apple-trees growing nearby.
Byteasar has learned about his wife's plans just before the final match of the World Cup in soccer. He knows that his wife is keen about the garden and, therefore, that it must be created instantly. To save some time, he asked her what exactly is her dream location of the garden - he knows that Byteen will surely check all the possibilities before making a final decision. Help Byteasar to find out how much time he has left, assuming that checking a single location for the garden takes Byteen exactly one second.
Input
The first line of the input contains one integer N, 1 <= N <= 10
5
, the number of apple-trees growing near Byteen's and Byteasar's house. For simplicity, the locations of trees are given in a Cartesian coordinate system. Each of the following N lines contains two space-separated integers X
i
and Y
i
, -10
6
<= X
i
, Y
i
<= 10
6
, the coordinates of the i-th apple-tree. No pair of coordinates appears in the input twice.
Output
Your program should print a single integer: the number of seconds Byteen will spend on checking all possible locations of the garden, each location containing apple-trees in all its corners.
Example
For the input data:
6
0 0
0 1
1 0
1 1
3 0
3 1
the correct result is:
1 | 33,333 |
Keyboard (STC06)
Byteman has received an extraordinary keyboard as a gift. The keyboard is a rectangle consisting of N rows and M columns with N × M keys placed on it. Moreover, all keys except the one in the top left corner are covered with domino tiles of size 1 × 2, so there are (N × M - 1) / 2 domino tiles in total. At any time, Byteman can move onto the free key one of the domino tiles adjacent to it by the shorter side. He can also press keys, but only if they are not covered.
Byteman would like to test (i.e., press) all the keys corresponding to vowels, that is, the letters
a
,
e
,
i
,
o
,
u
or
y
. What is the minimum number of tile moves necessary to do that?
Input
The first line of the input contains two integers N and M (1 ≤ N, M < 70) that describe the dimensions of the keyboard. The next N lines contain M lowercase letters of the English alphabet each, describing the rows of the keyboard. Each of the next N lines contains M characters describing placement of the domino tiles:
.
(ASCII code 46) denotes an uncovered key,
-
(ASCII code 45) denotes a key covered by a domino tile placed horizontally and
|
(ASCII code 124) - a key covered by a tile placed vertically.
Output
If it is not possible for Byteman to press all the keys corresponding to vowels, your program should output just the single word "
NIE
" (i.e.
no
in Polish). Otherwise output the minimum number of tile moves that Byteman must make in order to press all the requested keys.
Example
Input:
3 3
ytr
hgf
dsa
.--
|||
|||
Output:
2 | 33,334 |
Railway (STC07)
A railroad siding consists of two (dead-end) sidetracks 1 and 2. The siding is entered by track A, and left by track B.
There are N cars on track A, numbered from 1 to N. They are arranged in such a way that they enter the siding in the order a
1
, a
2
, a
3
... a
N
. The cars are to be transferred to the siding, so that they leave it by track B in the order 1, 2, 3 ... N. Each car is to be transferred once from track A to one of the sidetracks 1 or 2, and later (possibly after some transfers of the remaining cars) once from that sidetrack to the track B. The sidetracks are long enough to store even the longest trains, so there is no need to worry about their capacity.
Input
The first line of the standard input holds one integer N (1 ≤ N ≤ 10
5
) that denotes the number of cars for transfer. The second line stores the numbers a
1
, a
2
, a
3
... a
N
that are a permutation of 1, 2, 3 ... N (i.e., each a
i
belongs to {1, 2, 3 ... N}, and all these numbers are unique), separated by single spaces.
Output
The first line of the standard output should contain the word
TAK
(
yes
in Polish) if there is a way of transferring the cars so that they enter track B in the order 1, 2, 3 ... N, or the word
NIE
(
no
in Polish) if it is impossible. If the answer is
TAK
, the second line should give, separated by single spaces, the numbers of sidetracks (1 or 2) to which successive cars a
1
, a
2
, a
3
... a
N
are moved in a correct transfer. If there are several ways of making the transfer, choose the lexicographically smallest.
Example
For the input data:
4
1 3 4 2
the correct result is:
TAK
1 1 2 1
And for the input:
4
2 3 4 1
the correct result is:
NIE | 33,335 |
Kangaroos (STC08)
Byteasar, who is interested in wildlife photography, is planning a trip to Australia. He has started preparing his photographic equipment for taking pictures of kangaroos, and has to decide what items to pack. His equipment includes an extensive collection of photographic lenses with varying characteristics for different angles of view and focusing abilities. The best quality of pictures of animals, such as kangaroos, is achieved when the distance between the camera and the animal is within the optimal range of the lens.
Byteasar's trip passes through a sequence of access points for wildlife observation and photography. The Australian guides gave Byteasar a detailed description of these observation points-in particular, the distances at which kangaroos can be expected.
Obviously, not all the lenses from Byteasar's large collection will fit in his luggage, so some decisions must be made. Since Byteasar wishes to keep his lens-changes to a minimum, he wants to find-for each of the lenses-the longest contiguous sequence of observation points on the trip for which that lens is suitable. A lens is suitable for a given observation point if there exists a distance from the range of expected distances that lies within the optimal range of that lens.
Input
The first line of the standard input contains two integers, N and M (1 <= N <= 50000, 1 <= M <= 200000), where N is the number of observation points on the trip and M is the number of lenses in Byteasar's collection.
The next N lines describe the access points for wildlife observation and photography on Byteasar's trip. Each of these lines contains two integers, A
i
and B
i
(1 <= A
i
<= B
i
<= 10
9
), indicating that at the i-th observation point kangaroos can appear at a distance of A
i
to B
i
bytean feet, inclusive.
The next M lines describe the lenses. Each of these lines contains two integers, L
i
and R
i
(1 <= L
i
<= R
i
<= 10
9
), indicating that the i-th lens works best for kangaroos that are at a distance from L
i
to R
i
bytean feet from the camera, inclusive.
Output
The standard output should consist of M lines containing exactly one integer each. The i-th output line indicates the number of observation points in the longest
contiguous
segment of the trip where the i-th lens can be used by Byteasar. The lenses are numbered according to their order in the input file.
Example
For the input data:
3 3
2 5
1 3
6 6
3 5
1 10
7 9
the correct result is:
2
3
0 | 33,336 |
Aesthetic Text (STC09)
Let us consider a text consisting of N words numbered from 1 to N. We represent any of its decompositions into
K
lines by a sequence of numbers
(a
1
, a
2
, a
3
... a
k-1
)
, such that the words with numbers from 1 to a
1
are in the first line, the words with numbers from a
1
+1 to a
2
are in the second line, and so on, and finally, the words with numbers from a
K
-1 to N are in the last, K-th line.
Each word has a certain length (measured in the number of characters). Let length(x) denote the length of the word number x. Furthermore, every two adjacent words in a line are separated by a space of width of a single character. By length of the line we denote the sum of lengths of the words in this line, increased by the number of spaces between them. Let line(w) denote the length of the line number w. I.e., if the line number w contains the words with numbers from i to j inclusive, its length is:
line(w) = length(i) + length(i+1) + ... + length(j) + (j - i)
As an example, let us consider a text consisting of 4 words of lengths 4, 3, 2 and 5, respectively, and its decomposition (1, 3) into 3 lines. Then the length of the first line is 4, second is 6, and third is 5:
XXXX
(1st line)
XXX XX
(2nd line)
XXXXX
(3rd line)
We shall refer to the number
|line(1) - line(2)| + |line(2) - line(3)| + ... + |line(K-1) - line(K)|
as the coefficient of aestheticism of a decomposition of the given text into K lines. Particularly, if the decomposition has only one line, its coefficient of aestheticism is 0.
Needless to say, the smaller the coefficient, the more aesthetical the decomposition. We shall consider only these decompositions that have no line whose length exceeds some constant M. Of all such decompositions of a given text into any number of lines we seek the one most aesthetical, i.e. the one with the smallest coefficient of aestheticism. The aforementioned exemplary decomposition's coefficient is 3, and that is exactly the minimum coefficient of aestheticism for M = 6 and M = 7.
Task
Write a program that:
reads from the standard input the numbers M and N, and the lengths of the words,
determines the minimum coefficient of aestheticism for those decompositions, whose every line is of length not exceeding M,
writes the result to the standard output.
Input
The first line of the standard input contains the numbers M and N, (1 <= M <= 1000000, 1 <= N <= 2000) separated by a single space. The second, last line of the standard input contains N integers, denoting the lengths of subsequent words, 1 <= length(i) <= N for i = 1, 2, 3 ... N, separated by single spaces.
Output
The first and only line of the standard output should contain exactly one integer: the minimum coefficient of aestheticism for those decompositions, whose every line's length does not exceed M.
Example
For the input data:
6 4
4 3 2 5
the correct result is:
3
while for the following input data:
4 2
1 2
the correct result is:
0 | 33,337 |
Blockade (STC10)
There are exactly N towns in Byteotia. Some towns are connected by bidirectional roads. There are no crossroads outside towns, though there may be bridges, tunnels and flyovers. Each pair of towns may be connected by at most one direct road. One can get from any town to any other-directly or indirectly.
Each town has exactly one citizen. For that reason the citizens suffer from loneliness. It turns out that each citizen would like to pay a visit to every other citizen (in his host's hometown), and do it exactly once. So exactly N*(N-1) visits should take place. That's right,
should
. Unfortunately, a general strike of programmers, who demand an emergency purchase of software, is under way. As an act of protest, the programmers plan to block one town of Byteotia, preventing entering it, leaving it, and even passing through. As we speak, they are debating which town to choose so that the consequences are most severe.
Task
Write a programme that:
reads the Byteotian road system's description from the standard input,
for each town determines, how many visits could take place if this town were not blocked by programmers,
writes out the outcome to the standard output.
Input
In the first line of the standard input there are two positive integers: N and N (1 <= N <= 100000, 1 <= M <= 500000) denoting the number of towns and roads, respectively. The towns are numbered from 1 to N. The following M lines contain descriptions of the roads. Each line contains two integers X
i
and Y
i
(1 <= X
i
, Y
i
<= N) and denotes a direct road between towns numbered X
i
and Y
i
.
Output
Your programme should write out exactly N integers to the standard output, one number per line. The i-th line should contain the number of visits that could not take place if the programmers blocked the town no. i.
Example
For the input data:
5 5
1 2
2 3
1 3
3 4
4 5
the correct result is:
8
8
16
14
8 | 33,338 |
Spiky Mazes (SPIKES)
Jarmtin is interested in cultures and the history behind them. Of course this interest has a reason: as he studies the choivans' past he discovers the hidden entrances of mazes he knows contain valuable information. However there is a catch: the mazes contain spiky traps! Jarmtin is quite the agile type, but there is a limit to everyone, thus he will only be able to avoid a number of traps. This motivates the question can he make it through the mazes?
Input
The first line of a test case contains three integers n, m and j. n (2 ≤ n ≤ 40) the number of rows, m (2 ≤ n ≤ 40) the width of each row and j (0 ≤ j ≤ 20) the number of times Jarmtin can avoid spikes. Then n lines containing m characters; The character 'x' will be used for the place of the treasure, '@' for an entrance (which is also an exit), '#' for walls, '.' for a safe walking tile and 's' for spikes. Note that you cannot walk into walls and the maze is completely surrounded by walls outside what you can see. There is always at least one entrance/exit and always an x where the treasure is.
Output
You should output "SUCCESS" if Jarmtin can make it in and out alive, and "IMPOSSIBLE" if there is no way you can make it out alive.
Sample Input / Output
Example 1:
Input:
3 3 2
#@#
#s#
#x#
Output:
SUCCESS
Example 2:
Input:
4 4 3
####
@.s#
##.#
#xs#
Output:
IMPOSSIBLE | 33,339 |
Postering (POSTERIN)
All the buildings in the east district of Byteburg were built in accordance with the old architecture: they stand next to each other with no spacing in between. Together they form a very long chain of buildings of diverse height, extending from east to west.
The mayor of Byteburg, Byteasar, has decided to have the north face of the chain covered with posters. Byteasar ponders over the minimum number of posters sufficient to cover the whole north face. The posters have rectangular shape with vertical and horizontal sides. They cannot overlap, but may touch each other, i.e. have common points on the sides. Every poster has to entirely adjoin the walls of certain buildings and the whole surface of the north face has to be covered.
Task
Write a programme that:
reads the description of buildings from the standard input,
determines the minimum number of posters needed to entirely cover their north faces,
writes out the outcome to the standard output.
Input
The first line of the standard input contains one integer N (1 ≤ N ≤ 250000), denoting the number of buildings the chain comprises of. Each of the following N lines contains two integers D
i
and W
i
(1 ≤ D
i
, W
i
≤ 10
9
), separated by a single space, denoting respectively the length and height of the i-th building in the row.
Output
The first and only line of the standard output should contain one integer, the minimum number of rectangular posters that suffice to cover the north faces of the buildings.
Example
Input
5
1 2
1 3
2 2
2 5
1 4
Output
4 | 33,340 |
Tie the Rope (TIEROPE)
Sailor Crow'n-beard has many pieces of rope. Every piece has a different value and it is well known that money equals quality. Crow'n-beard wants you to create a program that given pieces of rope, creates a rope with the length as close as possible to his desired length (but never too short) while maximizing the quality.
Input
Input describes a single test case. The first line contains two integers
N
(1 ≤
N
≤ 80) and
L
(1 ≤
L
≤ 10000): the number of rope pieces Crow'n-beard and the desired length respectively. Then
N
lines will follow, each with two integers: the length
Li
(0 ≤
Li
< 2^31) followed by the value
Vi
(0 ≤
Vi
≤ 26843545) of the piece of rope. It is guaranteed that the sum of
Li
is never less than
L
.
Output
You should output the maximal total quality you can reach. Remember that the priority is to get the smallest total length that is still at least equal to
L
. Only then output the best total quality amongst equal length solutions.
Sample
Input:
4 4
20 2
1 4
3 4
4 7
Output:
8 | 33,341 |
Create Collections (IITKWPCO)
Little Feluda likes to play very much. As you know he only plays with numbers. So he is given n numbers. Now tries to group the numbers into disjoint collections each containing two numbers. He can form the collection containing two numbers iff small number in the collection is exactly half of large number.
Given n numbers, Find out how many maximum number of collections he can form ?
Input
T: number of test cases. (1 <= T <= 100).
For each test case:
First line will contain n : (1 <= n <= 100)
Then next line will contain n numbers single space separated. Range of each number will be between 1 and 10^6.
Output
For each test case, output maximum number of collections that can be formed.
Example
Input:
2
2
1 2
3
1 2 4
Output:
1
1 | 33,342 |
On the Plus Side (PLUS)
A man called Gerit Teeman was fascinated by the plus symbol and, to be honest, this symbol is actually quite interesting!
Begin by drawing an one. This will be the center of the plus symbol. Above this center draw the number two, below three, to the left four and the the right five. If you then 'replace' the center (either up, down, left or right), do the same, but when a place is already filled you leave it untouched.
To illustrate this we pick the place with the number two: Above it draw a two, the bottom is already filled so we leave it untouched, to the left we draw a four and the the right we draw a five. See the picture below:
It is not hard to see that the sum of the first plus symbol is 15 (the first symbol only containing 1 is NOT a plus symbol). The sum of the second symbol is already more difficult, summing up to 26. Now here comes the catch: depending on which number you pick to expand on, the number on positions can change. If we would have picked five to expand on instead of two, we will get the following:
As you can see the numbers differ from that of the first example. This time the sum is 25! On top of that, there can be multiple 'replaces', generating more number in the symbol. Your task is, depending on which way you expand to, give the sum of all the elements of plus symbol that you would obtain.
Input
First line contains an integer T (1 <= T <= 100) number of test cases. Each of the next T lines contains a string with letters 'L', 'R', 'U', 'D' and 'S' (separated by commas) which respectively mean left, right, up, down and stop. You should expand to the given direction, based on your last created expansion's center. Stop means you should finish and output the total sum to that point. The number of letters in the string will never exceed 10000.
Note that the first example was created by the string "U,S" and the second by the string "R,S".
Output
For each test case output a single integer in a separate line: the total sum of all numbers contained in the created symbol.
Sample:
Input:
2
U,S
S
Output:
26
15 | 33,343 |
Lennys Lucky Lotto Lists (GNYR04C)
Lotto is a lottery, typically with an accumulating jackpot, in which participants play numbers of their choice in a random drawing. Lenny likes to play the lotto in Lincoln county Louisiana. In the game, he picks a list of
n
numbers in the range from 1 to
m
. If his list matches the drawn list, he wins the big prize, a lifetime supply of large lemons.
Lenny has a scheme that he thinks is likely to be lucky. He likes to choose his list so that each number in it is at least twice as large as the one before it. So, for example, if
n
= 4 and
m
= 10, then the possible lucky lists Lenny could pick are:
1 2 4 8
1 2 4 9
1 2 4 10
1 2 5 10
Thus Lenny has 4 lists to choose from.
Your job, given
n
and
m
, is to count how many lucky lists Lenny has to his disposal.
Input
The first line of input is a single non-negative integer, which is the number of data sets to follow. All data sets should be handled identically. The next lines, one per data set, contain two integers,
n
and
m
. It is guaranteed that 1 ≤
n
≤ 10 and 1 ≤
m
≤ 2000 and
n
≤
m
.
Output
For each data set, print a line like the following:
Data set
i
:
n
m
number
where
i
is the data set number (beginning with 1), and
number
is the maximum number of lucky lists corresponding to the provided values of
n
and
m
.
Example
Input
1
4 10
Output
Data set 1: 4 10 4 | 33,344 |
Histology Assistant (GNYR04I)
An application to assist in the analysis of tissue samples is to work as follows. A digital microphotograph of a stained tissue sample is scanned to identify stained pixels. For each region of stained pixels, an outline of the region is obtained. The outline is then analyzed for shape indicators of disease and the outlines (color-coded for possible disease) are overlaid on the microphotograph as it is displayed to the pathologist.
This problem is to write a program, which processes a bitmap of stained and unstained pixels, finds regions of stained pixels and, for each region, outputs the outline of the region. Regions with fewer stained pixels than a minimum size are ignored. Only the outer boundary is computed (interior holes are ignored).
A pixel is adjacent to another pixel if the second pixel is directly above, directly below, directly left or directly right of the first pixel. Two stained pixels are connected if there is a sequence of stained pixels starting with one of the pixels and ending with the other for which each pixel in the sequence is adjacent to the next. A regionof stained pixels is a set of stained pixels, all of which are connected to a single stained pixel. A stained pixel is a boundary pixel of its region if at least one of the pixels adjacent to it is not stained. (All pixels immediately outside the bitmap are considered unstained so that pixels on the edge of the bitmap are boundary pixels.) In the example below, there are 4 regions (stained pixels are '
X
', unstained are '
.
').
........................................
.XX.....................................
..X.................XXX......XXX........
.....................XXX....XXX.........
.......XXX............XXX..XXX..........
.....XXXXXXX...........XXXXXX...........
....XXXXXXXXX...........XXXX............
...XXXX...XXXX...........XX.............
..XXX.......XXX.........................
..XXX.......XXX........XXXXXXX..........
.XXX.........XXX.......XXXXXXX..........
.XXX.........XXX.......XXXXXXX..........
.XXX.........XXX.......XXXXXXX..........
..XXX.......XXX...........X.............
..XXX.......XXX...........X.............
...XXXX...XXXX.........XXXXXXX..........
....XXXXXXXXX..........XXXXXXX..........
.....XXXXXXX...........XXXXXXX..........
.......XXX.............XXXXXXX..........
........................................
Outlines are to be specified as the left most point of the top most line of the region, a count of boundary pixels and a sequence of moves from one boundary pixel to the next clockwise using the codes (up =
A
, up right =
B
, etc.):
H A B
G C
F E D
Rows are numbered from top to bottom beginning with 1. Columns are numbered from left to right beginning with 1. For example the outline of the 'v' shaped region above would be:
3 21 22
CCDDDCBBBCCFFFFFGHHHHH
Input
Input is a sequence of problem instances. Each problem instance begins with a line containing 3 decimal numbers: row-count,column-count and minimum-number-of-pixels. This line is followed by row-count lines of column-count characters. Each character is either a period (
.
) for an unstained pixel or an upper-case '
X
' for a stained pixel. The input ends when the row-count is 0. Row-count will be at most 47, column-count will be at most 63 and minimum- number-of-pixels will be at least 2.
Output
For each problem instance, the output begins with a line starting with a decimal integer giving the number of components of at least minimum-number-of-pixels stained pixels. This is followed by the description of the boundary of each component. The boundaries are to be listed in the order that a first pixel of the component appears while scanning across lines from left to right with line scanned from top to bottom. For each component, the output begins with a line giving the row number of the start pixel, thecolumn number of the start pixel and the number of pixels in the boundary as decimal integers separated by a single space. This line is followed by lines of direction codes '
A
' through '
H
'. Each line shall have 40 characters except the last line.
Sample
Input:
20 40 4
........................................
.XX.....................................
..X.................XXX......XXX........
.....................XXX....XXX.........
.......XXX............XXX..XXX..........
.....XXXXXXX...........XXXXXX...........
....XXXXXXXXX...........XXXX............
...XXXX...XXXX...........XX.............
..XXX.......XXX.........................
..XXX.......XXX........XXXXXXX..........
.XXX.........XXX.......XXXXXXX..........
.XXX.........XXX.......XXXXXXX..........
.XXX.........XXX.......XXXXXXX..........
..XXX.......XXX...........X.............
..XXX.......XXX...........X.............
...XXXX...XXXX.........XXXXXXX..........
....XXXXXXXXX..........XXXXXXX..........
.....XXXXXXX...........XXXXXXX..........
.......XXX.............XXXXXXX..........
........................................
12 40 4
.X.X.X.X.X.X......XX...XXXXXXXXXXXXXXXX.
.XXX.XXX.XXX......XX..XXXXXXXXXXXXXXXXXX
.X...X...X........XX..XX.............XXX
.X.X.X.X.X.X......XX..XX...XXXXXXXX...XX
.XXX.XXX.XXX......XX..XX..XXXXXXXXXX..XX
.X...X...X........XX..XX..XX......XX..XX
.X.X.X.X.X.X......XX..XXX........XXX..XX
.XXX.XXX.XXX......XX..XXXXXXXXXXXXXX..XX
.X...X...X........XX...XXXXXXXXXXXX...XX
.X.X.X.X.X.X......XXX................XXX
.XXXXXXXXXXX......XXXXXXXXXXXXXXXXXXXXXX
...................XXXXXXXXXXXXXXXXXXXX.
0 0 0
Output:
3
3 21 22
CCDDDCBBBCCFFFFFGHHHHH
5 8 36
CCDCDDDEDEEFEFFFGFGGHGHHHAHAABABBBCB
10 24 38
CCCCCCEEEGGFEDCCEEEGGGGGGAAACCBAHGGAAA
2
1 2 103
DBEGFEDBEGFEDBEGFEDBDBAAAAAAAAADBEGFEDBE
GFEDBEGFEDBDBAAAAAAAAADBEGFEDBEGFEDBEGFE
DBEGGGGGGGGGGAAAAAAAAAA
1 19 159
CEEEEEEEEDDCCCCCCCCCCCCCCCBBAAAAAHHGGGGG
GGGGGGGFEEEDDCCCCCCCBBHGGGGGFGABCCCCCCCD
EEEFGGGGGGGGGGGHAAAAAABCCCCCCCCCCCCCCCDE
EEEEEEEEFGGGGGGGGGGGGGGGGGGGHAAAAAAAAAA | 33,345 |
Mr Youngs Picture Permutations (GNYR04H)
Mr. Young wishes to take a picture of his class. The students will stand in rows, with each row no longer than the row behind it and the left ends of the rows aligned. For instance, 12 students could be arranged in rows (from back to front) of 5, 3, 3 and 1 students.
X X X X X
X X X
X X X
X
In addition, Mr. Young wants the students in each row arranged so that heights decrease from left to right. Also, student heights should decrease from the back to the front. Thinking about it, Mr. Young sees that for the 12-student example, there are at least two ways to arrange the students (numbers represent heights, with 1 meaning the tallest):
1 2 3 4 5 1 5 8 11 12
6 7 8 2 6 9
9 10 11 3 7 10
12 4
Mr. Young wonders how many different arrangements of the students there might be for a given arrangement of rows. He tries counting by hand starting with rows of lengths 3, 2 and 1 and counts 16 arrangements:
123 123 124 124 125 125 126 126 134 134 135 135 136 136 145 146
45 46 35 36 34 36 34 35 25 26 24 26 24 25 26 25
6 5 6 5 6 4 5 4 6 5 6 4 5 4 3 3
Mr. Young sees that counting by hand is not going to be very effective for any reasonable number of students. He asks you to help out by writing a computer program to determine the number of different arrangements of students for a given set of rows.
Input
The input describes a series of test, each described in two lines. The first line gives the number of rows,
k
, as a decimal integer. The second line contains the lengths of the rows from back to front (
n
1
,
n
2
...
n
k
) as decimal integers separated by single spaces. The problem set ends with a line with a row count of 0. There will never be more than 5 rows and the total number of students,
N
, (sum of the row lengths) will be at most 30.
Output
For each test case output a single integer: The number of arrangements of
N
students into the given rows, so that the heights decrease along each row from left to right and along each column from back to front (assume that all heights are distinct). The results should be in separate lines. The input data will be chosen so that the result will always fit in an unsigned 32-bit integer.
Sample
Input
1
30
5
1 1 1 1 1
3
3 2 1
4
5 3 3 1
5
6 5 4 3 2
2
15 15
0
Output
1
1
16
4158
141892608
9694845 | 33,346 |
Commando (APIO10A)
You are the commander of a troop of n soldiers, numbered from 1 to n. For the battle ahead, you plan to divide these n soldiers into several commando units. To promote unity and boost morale, each unit will consist of a contiguous sequence of soldiers of the form (i, i+1 ... i+k).
Each soldier i has a battle effectiveness rating xi. Originally, the battle effectiveness x of a commando unit (i, i+1 ... i+k) was computed by adding up the individual battle effectiveness of the soldiers in the unit. In other words, x = x
i
+ x
i+1
+ ··· + x
i+k
.
However, years of glorious victories have led you to conclude that the battle effectiveness of a unit should be adjusted as follows: the adjusted effectiveness x is computed by using the equation x = ax
2
+ bx + c, where a, b, c are known coefficients (a < 0), x is the original effectiveness of the unit.
Your task as commander is to divide your soldiers into commando units in order to maximize the sum of the adjusted effectiveness of all the units.
For instance, suppose you have 4 soldiers, x
1
= 2, x
2
= 2, x
3
= 3, x
4
= 4. Further, let the coefficients for the equation to adjust the battle effectiveness of a unit be a = −1, b = 10, c = −20. In this case, the best solution is to divide the soldiers into three commando units: The first unit contains soldiers 1 and 2, the second unit contains soldier 3, and the third unit contains soldier 4. The battle effectiveness of the three units are 4, 3, 4 respectively, and the adjusted effectiveness are 4, 1, 4 respectively. The total adjusted effectiveness for this grouping is 9 and it can be checked that no better solution is possible.
Input
First Line of input consists
number of cases T
.
Each case consists of three lines. The first line contains a positive integer n, the total number of soldiers. The second line contains 3 integers a, b, and c, the coefficients for the equation to adjust the battle effectiveness of a commando unit. The last line contains n integers x1, x2 ... xn, separated by spaces, representing the battle effectiveness of soldiers 1, 2 ... n, respectively.
Constraints
T ≤ 3
n ≤ 1, 000, 000
−5 ≤ a ≤ −1
|b| ≤ 10, 000, 000
|c| ≤ 10, 000, 000
1 ≤ xi ≤ 100
Output
Output each answer in a single line.
Sample
Input:
3
4
-1 10 -20
2 2 3 4
5
-1 10 -20
1 2 3 4 5
8
-2 4 3
100 12 3 4 5 2 4 2
Output:
9
13
-19884
(Official dataset of APIO was NOT used in this problem.) | 33,347 |
Unequalled Consumption (NWERC05)
The Association of Candy Makers is preparing to launch a new product. Its idea is old with a novel twist: it simply sells boxes of candies. But since people are what they consume and everyone wants to be unique these days, the ACM wants
every
candy box to be unique, in the sense that no two boxes should contain the same composition of candy types.
The ACM is only able to make a small number n of different types of candy, but while limited in imagination, it is virtually limitless in resources, so it is able to produce as many as it wants of each type of candy. Furthermore, the candy types have different weights (though some may weigh the same), and in order to simplify pricing matters, the ACM wants all candy boxes to have the same total weight.
With these restrictions, the ACM will only be able to make a limited number of boxes. For instance, if there are three types of candy, weighing 5, 5 and 10 grams respectively, 4 different boxes can be made with total weight 10 grams (using either two of type 1, or two of type 2, or one of type 3, or one each of types 1 and 2). The ACM would like to be able to make at least one box for everyone in the cosmos. So, given queries in the form of the number of people P in the cosmos, your job is to find the smallest possible total weight w such that P different boxes containing exactly w grams of candies can be made.
Input
The input consists of several data sets (at most 20). Each data set consists of four lines. The first line contains an integer 1 ≤ n ≤ 5, the number of candy types. The next line contains n integers w
1
, ... w
n
, where 1 ≤ w
i
≤ 10 is the weight (in grams) of the i'th candy type. The third line contains an integer 1 ≤ q ≤ 10, the number of queries. The last line of a data set contains q integers P
1
, ... P
q
, where 1 ≤ P
j
≤ 10
15
is the j'th query. Input is terminated by an incomplete data set where n = 0, which should not be processed.
Output
For the i'th data set, write a line
"Set i"
, followed by q lines giving, for each query P
j
, the minimal possible positive weight W
j
(in grams) of a candy box. If there is no weight W
j
such that at least P
j
candy boxes can be made, print "
no candy for you
" for that query. You may assume that W
j
, if it exists, will be at most 100 · P
j
.
Sample
Input:
3
5 5 10
1
4
4
3 1 4 2
2
142 700
1
10
1
100
0
Output:
Set 1
10
Set 2
23
42
Set 3
no candy for you
be careful SPOJ watch you: if I found anyone submit judge solution I will disqualify this submission. | 33,348 |
Dark roads (ULM09)
Economic times these days are tough, even in Byteland. To reduce the operating costs, the government of Byteland has decided to optimize the road lighting. Till now every road was illuminated all night long, which costs 1 Bytelandian Dollar per meter and day. To save money, they decided to no longer illuminate every road, but to switch off the road lighting of some streets. To make sure that the inhabitants of Byteland still feel safe, they want to optimize the lighting in such a way, that after darkening some streets at night, there will still be at least one illuminated path from every junction in Byteland to every other junction.
What is the maximum daily amount of money the government of Byteland can save, without making their inhabitants feel unsafe?
Input
The input file contains several test cases. Each test case starts with two numbers
m
and
n
, the number of junctions in Byteland and the number of roads in Byteland, respectively. Input is terminated by
m = n = 0
. Otherwise,
1 ≤ m ≤ 200000
and
m-1 ≤ n ≤ 200000
. Then follow
n
integer triples
x, y, z
specifying that there will be a bidirectional road between
x
and
y
with length
z
meters (
0 ≤ x, y < m
and
x ≠ y
). The graph specified by each test case is connected. The total length of all roads in each test case is less than 2
31
.
Output
For each test case print one line containing the maximum daily amount the government can save.
Sample
Input:
7 11
0 1 7
0 3 5
1 2 8
1 3 9
1 4 7
2 4 5
3 4 15
3 5 6
4 5 8
4 6 9
5 6 11
0 0
Output:
51 | 33,349 |
Product of factorials (FACTMUL)
You need to find the product of first n factorials 1! * 2! * ... * n! modulo 109546051211.
Input
One integer n (1 <= n <= 10000000)
Output
The answer.
Example
Input:
5
Output:
34560 | 33,350 |
Product of factorials (medium) (FACTMULM)
You need to find the product of the first
n
factorials, so 1! * 2! * ... *
n
! modulo
p
, where
p
=63303212889375877567328165411288303907410870625225931671654121339922293885519921.
Input
An integer
T
, denoting the number of testcases (
T
≤10). Each of the
T
following lines contains a positive integer, where
n
≤ 10^8.
Output
Output
T
lines, the case number followed by the answer. See the sample output for the correct format!
Example
Input:
7
1
5
100
429
1000
1000000
100000000
Output:
Case 1: 1
Case 2: 34560
Case 3: 30320185692040509343149810686654647278680728299485184027723296362520679295668953
Case 4: 49116522183503229678644619968184124916695876848076217702050317922528502280661110
Case 5: 38310494067749735972957877453766730719859042112664856832928508845605975573300554
Case 6: 59623175509081913319809873890125269865036398088611331352359071382248773213856402
Case 7: 43046234475587180053977224639514165196068475389708692929440906111909653614719387 | 33,351 |
The Sierpinski Fractal (ULM02)
Consider a regular triangular area, divide it into four equal triangles of half height and remove the one in the middle. Apply the same operation recursively to each of the three remaining triangles. If we repeated this procedure infinite times, we'd obtain something with an area of zero. The fractal that evolves this way is called the Sierpinski Triangle. Although its topological dimension is
2
, its Hausdorff-Besicovitch dimension is
log(3)/log(2)~1.58
, a fractional value (that's why it is called a fractal). By the way, the Hausdorff-Besicovitch dimension of the Norwegian coast is approximately
1.52
, its topological dimension being
1
.
For this problem, you are to outline the Sierpinski Triangle up to a certain recursion depth, using just ASCII characters. Since the drawing resolution is thus fixed, you'll need to grow the picture appropriately. Draw the smallest triangle (that is not divided any further) with two slashes, to backslashes and two underscores like this:
/\
/__\
To see how to draw larger triangles, take a look at the sample output.
Input
The input contains several testcases. Each is specified by an integer
n
. Input is terminated by
n = 0
. Otherwise
1 ≤ n ≤ 10
indicates the recursion depth.
Output
For each test case draw an outline of the Sierpinski Triangle with a side's total length of
2
n
characters. Align your output to the left, that is, print the bottom leftmost slash into the first column. The output must not contain any trailing blanks. Print an empty line after each test case.
Sample
Input:
3
2
1
0
Output:
/\
/__\
/\ /\
/__\/__\
/\ /\
/__\ /__\
/\ /\ /\ /\
/__\/__\/__\/__\
/\
/__\
/\ /\
/__\/__\
/\
/__\ | 33,352 |
Hall of Fountains (ULM2H)
The Museum of Modern Art has a really exciting exhibition: a kind of a longish hall composed of a sequence of quadratic-shaped rooms. Each room is equipped with a water fountain. Each fountain is characterized by a number
p
and acts independent of the others. It will be turned on for exactly
p
seconds, then it will be turned off for exactly
p
seconds, then on again, then off again, and so on for good. However, different fountains may have different values of
p
. And even if they share the same value, they still may perform not identically, for they might have been started at different times.
You stand in front of the first room, and want to cross the hall to the other end. Each of your steps takes exactly 1 second. You are able to move one room forward (unless you already reached the other end), one room backward (unless you are at the beginning), or just stay at your current position. Calculate the shortest time to reach the other end, if it is possible at all.
Since you do not want to get wet, you can only move into a room where the water fountain will be off during the second after your step. For example, suppose that the fountain in the next room behaves so, that it is on at times 0, 1, 2, then off at times 3, 4, 5, 6, then on at times 7, 8, 9, 10, then off again (which indicates
p=4
with an offset of 7). Then, you can move at time 2 into the room, arriving there at time 3, when the fountain is off. But you cannot move at time 6 into the room, because at time 7 it will be on.
Input
The input contains several test cases. Each test case starts with the number of fountains
n
. Input is terminated by
n=0
. Otherwise,
1 ≤ n ≤ 100
. Then follow
n
numbers
p
i
denoting the time each fountain is on and off, where
0 ≤ p
i
≤ 10
. A value of
0
for
p
i
indicates that fountain
i
is out of order (i.e. constantly off). Then follow
n
numbers
q
i
denoting the offset of each fountain, where
0 ≤ q
i
<2*p
i
, unless the fountain is out of order, in which case
q
i
is meaningless. Otherwise it means that fountain
i
will be on at time
q
i
, but off just one second before.
Output
For each test case output on a line a single number
t
denoting the shortest time needed to reach the end of the hall (i.e. to enter the place after the last room). Assume, that you are in front of the first room at time
0
(i.e. you can enter the first room at time
1
, if the fountain is off at time
1
). If it is impossible to go through the hall of fountains, print
0
instead.
Sample
Input:
3
0 0 0
0 0 0
4
6 3 3 4
2 3 0 4
2
1 1
0 0
0
Output:
4
11
0 | 33,353 |
California Jones and the Gate to Freedom (ULM02C)
California Jones (the sister of famous Indiana Jones) once again faced a seemingly intractable problem. Her only hope was in you. She knew you were a computer scientist and you might have a clue.
Jones calls you on the video-phone and tells you the facts: she walked into a trap and now stands in front of a huge gate. On the left side strange signs can be seen while
n
stones lie on the right side. In front of the gate there are exactly
n/2
holes. Says Jones, "I suppose I have to take exactly half of the stones from the right side and put them into the holes." Ancient writings confirm her conjecture. According to the writings it does not matter which hole a stone is placed into. It is only important that the right stones are chosen.
Nearby, Jones found a stone board, too, but was unable to interpret. It made sense to you though. It was a hint on how to sort the various possibilities of chosing
n/2
stones.
But you couldn't yet figure out about the zeros and the ones. So you asked Jones who replied that "the same symbols I saw on the left side of the gate - only they were somewhat longer sequences. But I haven't met such a primitive civilization yet."
Now everything was clear to you: the symbols were the representation of a binary number - and it indicated which stones to choose. Simply ingenious! Jones was enthusiastic about you.
But it was impossible for Jones to calculate for a given binary number the corresponding stones. So she instructed you to write a program to solve the task and help her through the gate to freedom. Five hours later, she would call back.
Take a thorough look at the figure to the left depicting the stone board, as well as the sample input and output, to figure out how to solve Jones' problem.
Input Specification
The input contains several testcases. Each starts with the number of stones
n
. Input is terminated by
n = 0
. Otherwise,
n
is even and
2 ≤ n ≤ 32
. The next
n
integers identify the stones. A test case is further subdivided into
k
(sub-) test cases,
k
being the next number in the input file. Then follow
k
times a bit string
b
(encoding a non-negative integer) and
n / 2
distinct integers identifying the set of chosen stones. No invalid stones will be chosen and the length of
b
will not exceed
30
.
Output Specification
For each (sub-) test case generate a line containing
TRUE
, if the chosen stones may be laid into the holes, and
FALSE
otherwise.
Sample Input
4
12 50 74 34
1
00
50 12
8
45 23 86 43 90 76 12 74
2
111001
86 43 90 74
010001
45 86 43 90
4
12 50 74 34
2
101
34 74
110
34 74
0
Sample Output
TRUE
TRUE
FALSE
TRUE
FALSE | 33,354 |
Balanced Food (ULM02B)
Computer scientists live on pizza. Now the doctors say this is no good. We ought to eat more balanced. So you put your really large pizza onto your table and eat slice-by-slice carefully watching that the rest of your meal stays where it is - on the table.
Since computer scientists love pizza, their favourite table is shaped like a slice of pizza. However, different people may have different-sized tables. Everyone has his own preference for the number of slices a pizza has to be cut to. However, all agree that the slices must have identical size. Write a program to help the poor pizza lovers!
Input
The input file contains several test cases. Each test case starts with the number of slices
n
the pizza is cut to. Input is terminated by
n = 0
. Otherwise,
1 ≤ n ≤ 9
. Then follow 9 floating-point numbers
p
x
, p
y
, r, t
x
, t
y
, u
x
, u
y
, v
x
, v
y
specifying the coordinates of the center
p
of the pizza, its radius, and the coordinates of three points
t, u, v
. They define the three corners of the slice-shaped table in counter-clockwise order, with
t
being the center.
The pizza is a homogeneous two-dimensional circular object. There is always a cut from its center parallel to the x-axis towards increasing x-values. The remaining pizza stays connected during the whole process, no matter what slices are removed. The distances from
t
to
u, v
are equal except for very small rounding errors. Tables are never larger than a half-circle.
Output
For each test case output on a line some possible ordering of slices, so that during the whole process of eating the pizza it does not fall down the table. Slices are numbered counter-clockwise starting with 1 directly above the positive x-axis.
If several such ordering exist, choose the lexicographically first one. If no ordering of slices exists, so that the pizza does not fall down, output a line containing the word "impossible" instead.
Remark
A connected, rigid, flat object remains fixed on a convex, flat surface if and only if the object's center of gravity lies above the surface. The x-coordinate, for example, of the center of gravity of an object
s
can be calculated by (∫
s
x
d
s
) / (∫
s
d
s
). Likewise, the y-coordinate can be expressed as (∫
s
y
d
s
) / (∫
s
d
s
). Note that the denominator of these expressions gives the area of
s
.
Sample
Input:
2 (-3.0,-1.0) 1.0 (-3.0,-1.1) (-1.5,0.4) (-4.5,0.4)
9 (2.0,1.0) 1.0 (0.0,0.0) (1.0,-1.0) (-1.0,1.0)
0
Output:
2 1
impossible | 33,355 |
Breaking String (BRKSTRNG)
A certain string-processing language allows the programmer to break a string into two pieces. Since this involves copying the old string, it costs n units of time to break a string of n characters into two pieces. Suppose a programmer wants to break a string into many pieces. The order in which the breaks are made can affect the total amount of time used. For example, suppose we wish to break a 20 character string after characters 3, 8, and 10 (numbering the characters in ascending order from the left-hand end, starting from 1). If the breaks are made in left-to-right order, then the first break cost 20 units of time, the second break costs 17 units of time, and the third breaks costs 12 units of time, a total of 49 units of time (see the sample below). If the breaks are made in right-to-left order, then the first break costs 20 units of time, the second break costs 10 units of time, and the third break costs 8 units of time, a total of 38 units of time.
The cost of making the breaks in left-to-right order:
thisisastringofchars (original)
thi sisastringofchars (cost: 20 units)
thi sisas tringofchars (cost: 17 units)
thi sisas tr ingofchars (cost: 12 units)
Total: 49 units.
The cost of making the breaks in right-to-left order:
thisisastringofchars (original)
thisisastr ingofchars (cost: 20 units)
thisisas tr ingofchars (cost: 10 units)
thi sisas tr ingofchars (cost: 8 units)
Total: 38 units.
Input
There are several test cases! In each test case, the first line contains 2 integers N (2 ≤ N ≤ 10000000) and M (1 ≤ M ≤ 1000, M < N). N is the original length of the string, and M is the number of the breaks. The following lines contain M integers Mi (1 ≤ Mi < N) in ascending order that represent the breaking positions from the string's left-hand end. Read input till EOF.
(There wont be more than
100
cases)
Output
For each test case, output in one line the least cost to make all the breakings.
Example
Input:
20 3
3 8 10
20 4
2 3 8 10
Output:
37
40 | 33,356 |
Enjoy Sum with Operations (SUMSUM)
You are given N numbers of the array (N ≤ 100000), all less than 10
8
and greater than 0.
Now, you are given 2 types of queries:
"1 x i"
: Change the i-th number to x. (0 ≤ x ≤ 10
8
)
"2 Op i1 i2"
: Compute the sum of all two elements taken at a time within index i1 to i2 (both inclusive) under the operation Op.
Op could be XOR, OR or AND.
For example, let N=4, Query=3 and
"10 20 30 40"
be the Initial array.
Query:
2 OR 1 3
1 0 1
2 OR 1 3
Answer:
2 OR 1 3 → (10 OR 20) + (20 OR 30) + (10 OR 30)
1 0 1 → Now array becomes 0 20 30 40
2 OR 1 3 → (0 OR 20) + (20 OR 30) + (0 OR 30)
Example
Input:
4 3
10 20 30 40
2 OR 1 3
1 0 1
2 OR 1 3
Output
90
80
NOTE:
If i1 is equal to i2, always output 0.
Click here to see my set of problems at Spoj. | 33,357 |
Enjoy Adding GP to Series (ADDGP)
You are initially given an empty array of Size
N
(<=100000). (i.e. each element is 0).
Given 2 <=
R
<=10
9
.
Now you are given 3 types of query:
"0 St i1 i2"
: means add (St, St*R, St*R^2, ...) GP from i1 to i2 respectively. (Means add the GP with start term St and common ratio R in the series beginning from i1 and ending at i2.)
"1 i j"
: means find the sum of values of the array from index
i
to index
j
with modulo 1000000007.
"2 i"
: resets the
i
-th index array to 0.
Constraints
Queries <=90000
1 <= St <= 10
9
Input
First Line contains
N
R
Q
.
Then Follows
Q
lines, each line can be of any 3 types described above.
Output
Output only second type of Query.
Example
Input:
2 2 3
0 2 1 2
1 1 2
1 2 2
Output:
6
4
Click here to see my set of problems at Spoj. | 33,358 |
Coder Express 3!! (CODERE3)
Mr Durgeshwara was very impressed by Rahul. But now he was in trouble. He has already fixed his daughter's marriage with Thangabali who was the best coder of his town. He got an idea and arranged a contest between Rahul and Thangabali. They have to solve a problem at the same time and whoever solves first will marry Meenamma. Rahul was not such a good coder and was also getting help from Meenamma. Your task is to help Thangabali to solve the problem to create a twist in story.
The problem was that there are large number of building in the town which are of different heights and all the building are in a single line.
You have to find the maximum possible length of the subsequences of buildings which are possible which are first increasing in heights and then decreasing! Please Note: the heights of the building in the subsequences should be strictly increasing and then strictly decreasing.
Input
First line contains an integer T (1 ≤ T ≤ 100) that represents the number of test cases. Then follows the T containing the integer N (1 ≤ N ≤ 1000) specifying the total number of elements and the next line contains the N integers A1, A2, A3 ... An (1 ≤ Ai ≤ 1000)
Output
For each test case, print only one line, the maximum length of such sequence.
Example
Input:
2
10
1 3 5 6 4 8 4 3 2 1
6
8 6 3 4 2 1
Output:
9
5
Explanation
For the first test case the subsequence is : 1 3 5 6 8 4 3 2 1. For the second test case it is : 8 6 4 2 1 | 33,359 |
Vending Machine (AUT)
Byteasar studies computer science at the University of Bytetown. There is a snack vending machine at his faculty that sells
n
types of snacks, numbered
1
through
n
. Snacks of different types may have different price, since they differ in size and flavor.
Recently Byteasar discovered that the vending machine is broken. If one buys a snack of type
i
, the vending machine additionally dispenses one snack of each of the types
1
,
2 ... i-1
, provided that snacks of these types are available (if there are no snacks of some of the types
1
,
2 ... i-1
, simply no snack of this type is dispensed). Buying snack of type
i
is possible only if at least one snack of this type is available.
Byteasar decided to take advantage of the fault he discovered. He would like to find out what is the maximum total value (that is, the sum of prices) of snacks that he can obtain in the vending machine using a given amount of money. He does not have to use all the money.
Input
First line contains a single integer
t
representing the number of test cases to be solved. The description of
t
test cases follows.
The first line of each test case contains two integers
n
and
k
(1 ≤
n
≤ 40, 1 ≤
k
≤ 64000): the number of types of snacks and the amount of money that Byteasar has at his disposal. The second line holds
n
integers
c
1
... c
n
(1 ≤
c
i
≤ 40), the prices of snacks of respective types. The third line holds
n
integers
l
1
... l
n
(1 ≤
l
i
≤ 40), the quantities of snacks of respective types that are available in the vending machine.
Output
The output should contain one integer per test case: the total price of snacks that Byteasar can obtain in the vending machine using at most
k
units of money.
Example
Input:
1
6 8
7 2 3 5 7 2
1 3 0 3 2 1
Output:
30
Explanation of the example: Byteasar buys a snack of type 6. The vending machine dispenses one snack of each of the types 1, 2, 4, 5 and 6. Next, Byteasar buys a snack of type 4. In addition to this snack, the vending machine dispenses one snack of type 2.
Task author: Jakub Pachocki | 33,360 |
Equalize the Sectors (SECTORS)
Digo has a cylindrical box which is vertically partitioned into
N
contiguous sectors which are open from the top. Each Sectorial Compartment initially contains a fixed number of coins. Now Digo wants to fill each Sectorial Compartment with equal number of coins. But the problem is that, at a time he is only allowed to increment any two adjacent sectors with one coin each. Given an initial arrangement, you need to tell whether such equalization is possible or not.
Every sector
i
(for all (0 <
i
<
N
)) is adjacent to sector (
i + 1
) and sector
N
is adjacent to sector
1
.
Input
In first line, the number of test cases
T.
Each test case consists of a number
N,
followed by a line containing
N
space separated integers where
i
th
integer (
Mi
) denotes the number of coins in
i
th
sectorial compartment of the box (initially), in clockwise order.
Output
For every test case output “
YES
” for possible and “
NO
” for which equalization is not possible (Without quotes).
Constraints
1 <=
T
<= 1000
3 <=
N
<= 100 (Number of Sectorial Compartments)
1 <=
Mi
<= 10^9 (Number of coins in each Sectorial Compartment)
Sample Input
2
3
1 2 3
4
1 2 1 2
Sample Output
YES
NO | 33,361 |
Find the Treasure (DIGOKEYS)
A psychic lock-lover called Digo likes playing games with Locks and Keys and also has very good logic.
One day he buys a set of
N
boxes, each of them has an index between {
1, N
} (inclusive) and no two boxes have same index. There is a key inside every box except the
Nth
box which has great treasure. He eventually finds out that due to a defect in the manufacturing of the keys, most of them could open more than one box.
The rule is that you are allowed to open only one box with any key. Each box except the first is locked. Now as Digo couldn’t wait long to acquire that great treasure he requests you to find a method to open the last box starting with the key in the first box with minimum number of steps.
INPUT
In first line,
T
no. of test cases.
For every test case:
In first line, there is an integer
N
: (number of locks)
In next
N-1
lines, on the
i’th
line there is an integer
Mi
the number of boxes which the key present in the
i’th
box
can open. It is followed by the
Mi
integers (the indices of those boxes that can be opened by the key present in
i’th
box).
OUTPUT
For every test case:
one integer
q
, minimum number of boxes opened.
In the next line : the indices of the boxes opened in order separated by space. If there are many solutions print the one which is lexicographically smallest.
If there is no way to reach the last box print “-1”.
Each test case is to be followed by a blank line.
Constraints
1 <=
T
<= 10
2 <=
N
<= 100000
1 <=
Mi
<= 10
Sample Input
2
3
1 2
1 3
4
2 2 3
1 1
2 2 4
Sample Output
2
1 2
2
1 3 | 33,362 |
Game (DGAME)
Digo is planning to recruit members for his ACM team, he designs a game in which who ever beats him will be recruited in his team. Darshil is a friend of yours. You have to help him get recruited in Digo's ACM team.
There are
N
piles, where
i
th
pile contains either
2×i
or
2×i+1
stones. During the game, Darshil and Digo take turns and Darshil takes the first turn. In each turn they can select any pile containing 2 or more stones and then remove an
EVEN
number of stones from the selected pile. The player who can't make the next move loses the game.
You have to find:-
Number of ways in which stones can be put in those
N
piles. (Each way is distinct if any one pile has different number of stones). If number of ways is
M
then print
M
% 1000000007.
For each configuration of part-1 Darshil counted the number of ways he can choose the first move such that no matter how optimally Digo plays he wins. Find the integral part of average number of such ways of all the configurations.
Input
The first line contains an integer
T
(number of test cases).
Each of the next
T
lines contains a single positive integer
N
.
Output
T
lines containing two space-separated integers - the answers to the first and second parts of the questions.
Constraints
1 ≤
N
≤ 10
9
1 ≤
T
≤ 10
3
Example
Input:
3
1
2
3
Output:
2 1
4 1
8 0 | 33,363 |
Permutations (PSERVICE)
A website provides its users with a variety of services. There are a total of
K
services available on that website. At present there are
M
users/clients registered to the website.
Now each client of this service provider firm is to be allocated a project by the website which makes use of a string
A1, A2, A3 ... An
of
N
services all of which the website is providing. The order in which the services are executed
matters
(compiling and then linking is different from linking and then compiling). Also, in a particular project, the same services cannot be executed twice in succession. For example, compiling → linking → compiling is allowed, but linking → linking → compiling is not allowed because 'linking' comes twice in succession.
All the M clients will start working at the same time and the time taken for the execution of all services is equal. At a time, one service can be accessed by only one client as there is only one server. For eg. If there are 3 clients with projects –
A1, A2 ... An
;
B1, B2 ... Bn
and
C1, C2 ... Cn
, then
Ai
,
Bi
,
Ci
are pairwise distinct
for 1 <=
i
<=
N
. You need to find in how many ways in which the
M
clients can be allocated their projects.
Input
First line containing
T
(number of test cases).
For each test case one line containing 3 integers
N
,
M
and
K
.
Output
For each test case output a separate line containing the answer modulo 1000000007.
Constraints
1 <=
T
<= 10
0 <=
N
<= 1000000000
1 <=
M
<= 100
0 <=
K
<= 1000
Sample
Input
3
2 2 3
1 2 3
2 3 4
Output
18
6
264 | 33,364 |
SUMMING (SUMMING)
Find the sum of $x$ smallest distinct numbers of the series $2^i \times 3^j$ ($i, j \ge 0$).
the first number of the series is $1 = 2^0 \times 3^0$
the second number of the series is $2 = 2^1 \times 3^0$
the third number of the series is $3 = 2^0 \times 3^1$
the fourth number of the series is $4 = 2^2 \times 3^0$
the fifth number of the series is $6 = 2^1 \times 3^1$
As the sum can be huge print sum
modulo
$k$.
Input
The input contains 2 numbers $x$ and $k$: $1 \le x \le 10^{14}$, $1 \le k \le 10^8$
Output
The output contains sum of the first $x$ numbers of the series
modulo
$k$.
Example
Input:
1 1000
Output:
1
Input:
2 1000
Output:
3
Explanation:
$3 = 2^0 \times 3^0 + 2^1 \times 3^0 \pmod{1000}$.
Input:
4 1000
Output:
10
Input:
6 2
Output:
0
Input:
16 1000
Output:
300 | 33,365 |
Great Warrior (SNGGW)
This problem is about an imaginary game. First of all, define a
War Board
that is a
N x N square matrix
. Each matrix cell represents a warrior and the value written in the cell is the power of that particular warrior.
Rules for assigning powers of each warrior
1.
First start filling the main diagonal with numbers
1, 2, 3, 4 .... K
according to requirement. Starting of filling always be at the top corner.
2.
Now start filling the anti diagonal with numbers
k + 1, k + 2, k + 3, k + 4 .... L
according to requirement. Starting of filling always be at the bottom corner.
Don't forget that in case of filling the anti diagonal if there is any number already filled it will be modified by the current number that is to be filled, if that particular cell was empty
.
3.
Now fill all the empty cells, in
anti-clockwise spiral
filling manner. The first cell to be filled will be
2nd last column of first row
.
5 x 5 War Board
Description of game
The greatest warrior
W
of king Pushyamitra Shunga is having fight with Yavana warriors. W fights with one Yavana warrior
Y
at a time. Consider the followings
1.
Power_of_W is more than Yavanas
.
2.
W can defeat Y if
Power_of_W > Power_of_Y - 1
3.
After each win
Power_of_W decreases by Power_of_Y
4.
W can move to cells adjacent to it. If
Current_Cell_Location_of_W
is
(i, j)
then
Next_Cell_Location_of_W
will be one of
(i ± 1, j ± 1)
or
(i ± 1, j)
or
(i, j ± 1)
5.
W will win if W defeats Y such that
Power_of_Y = 1
, otherwise W is defeated.
What to code
You have to code to verify whether W wins or get defeated but don't forget the followings -
1.
The one cell location is of W and other cell locations are of Yavanas
2.
Its up to W to choose the Yavana warrior Y to fight with
3.
Its not necessary that W has to defeat all Yavanas,
W just want to win
[All the information required to solve this problem is provided in the description]
Input
First line of input is t, total number of test cases (t < 1001). Next t lines contains value of
N (2 < N < 1000).
Output
Output for each test case is single line printing either
DWON
Final_Power_of_W
(If W wins) or
DDOWN
(If W is defeated).
Example
Input:
1
5
Output:
DWON 15 | 33,366 |
Prime Generator The Easiest Question Ever (SNGPG)
Prime number questions are always being favorite to everyone. This question is extension to the problem
PRIME GENERATOR
. The question is very very simple and easier than that you cannot imagine. You have to count total number of such primes p in the range
[a ≥ 0, b > 0]
so that
(p
2
+ 1) or/and (p
2
+ 2) is/are prime(s).
Input
First line of input is t,
(t < 100)
total number of test cases. Next t lines contains two integers a and b separated by space.
a < 50001, b < 100001 and b > a
.
Output
In each line print total numbers of such prime numbers.
Example
Input:
2
0 1
4 5
Output:
2
0
[Consider 0 and 1 as prime numbers for this question] | 33,367 |
Cave (CAVE2)
Byteasar has discovered a cave. It appears that the cave contains n chambers connected with passages in such a way that there exists a single way of getting from any chamber to any other chamber.
The cave should now be examined more thoroughly, so Byteasar has asked his friends for help. They have all arrived at the cave and they are willing to divide themselves into groups. Each group should examine the same number of chambers, and each chamber should be examined by exactly one group. Additionally, for the groups not to interfere with each others' work, the members of each group should be able to move between the assigned chambers without passing through chambers assigned to other groups.
How many groups can the explorers be divided into?
Input
The first line of the input contains one integer n (2 ≤ n ≤ 3000000) denoting the number of chambers in the cave. The chambers are numbered
1
through
n
.
The following n - 1 lines describe connections between the chambers. The i-th of these lines contains an integer a
i
(1 ≤ a
i
≤ i) which represents a passage connecting chambers number i + 1 and a
i.
Output
Your program should output a single line containing all integers k, such that the chambers can be divided into k disjoint sets of equal size, and one can move between any two chambers belonging to the same set passing only through chambers from this set. The numbers should be written in an ascending order and separated with single spaces.
Example
Input:
6
1
2
3
3
5
Output:
1 3 6
Task author: Jakub Lacki | 33,368 |
Update Sub-Matrix & Query Sub-Matrix (USUBQSUB)
Updating and querying 1 dimensional arrays is a popular question. How about updating and quering sub-matrices of a matrix?
A sub-matrix will be depicted as (a, b), (c, d). This implies that it will include all the cells (x, y) such that a<=x<=c and b<=y<=d.
The matrix is indexed from [1..N][1..N], where N is the size.
You are given a matrix of size NxN, with each element initially set to 0. There are M queries and each query can be of one of the two types:
1 x1 y1 x2 y2: This query asks you to return the sum of all the elements in the sub-matrix (x1, y1), (x2, y2).
2 x1 y1 x2 y2 K: This query asks you to add K to each element in the sub-matrix (x1, y1), (x2, y2).
Input
The first line of input contains N, M.
The next M lines contain queries in the same forms as stated above.
You may assume that x1<=x2 and y1<=y2 for all queries.
Also N<=1000 and M<=10
5
. K<=10
9
Output
The answer to all the queries wherein you need to return the sum of elements in the sub-matrix, i.e., all the queries of type 1.
Sample Test Case
Input:
5 5
2 2 2 4 4 4
1 1 1 3 3
2 5 5 5 5 3
1 1 1 1 2
1 2 2 5 3
Output:
16
0
24
Note:
Please be careful with certain languages as the output may exceed the range of the data type used to store it. Please use 64-bit integers to store the results. For example, long long in C/C++. | 33,369 |
MAXSET (MAXSET)
Ram and Sharav are good programmers. Ram is teaching Sharav bubble sort. Whenever Ram swaps two elements in the array (while sorting), he ties a rope between the element which are swapped.
Find the size of the maximal set in the array in which none of the elements are connected with any other element after the bubble sort is done.
eg: { 1, 3, 2 }
1st iteration of bubble sort:
2 and 3 swapped so tie 2 with 3
{1, 2, 3}
2nd iteration
{1, 2, 3}
no swaps in this iteration so don't tie any element with any other element.
3rd iteration
{1, 2, 3}
no swaps in this iteration so don't tie any element with any other element.
after the end of bubble sort only 2 and 3 are tied together, so the answer for this example is 2 because the size of the maximal set in which none of the elements is not tied with any other element.
the possible maximal sets are {1, 2} (since 1 and 2 are not tied with a rope) and {1, 3} (since 1 and 3 are not tied with the rope.)
Possible subsets for this array are {1}, {2}, {3}, {1, 2}, {1, 3}, {3, 2} {1, 3, 2}, { }
out of these valid subsets are {1}, {2}, {3}, {1, 2}, {1, 3} In this valid subsets {1, 2} and {1, 3} are larger subsets. The size of both the subsets are 2, so the answer is 2.
Input
First line of input contains T - number of test cases.
First line of each test case contains n (1 ≤ n ≤ 100000) - number of elements in the array.
Second line of each test case contains n elements of the array.
output
Print the size of the maximal set (for each test case print a new line.)
Example
(from the example explained above)
Input
1
3
1 3 2
Output:
2
Note: ropes are tied between two elements which are swapped while executing the sort routine. (Bubble sort). We need the size of the set containing the maximum number of elements which are not connected to any other element in the set. | 33,370 |
Help Donn (HELPDONN)
Enigma Treasure Hunt
KaushikRamDonn went to Enigma and registered for the Treasure Hunt. Following are the rules for Enigma Treasure hunt,
Donn has to go from 1st stage to nth stage in a sequential order (only after completing stage 1, he can go to stage 2, then to stage 3) and collect treasures in a bag.
Donn will be given only k bags at the time of registration.
There are bags capable of holding all possible weights and is infinite in number. Donn is free to choose any bags capable of holding any weight (but all the k bags should be capable of holding the same weight.) Pandian, the organiser will give the bag to Donn.
once the game is started, Donn cant exchange his bag.
While going through different stages, if Donn couldn't accommodate the treasure in a bag, he will tie the bag and give it to Pandian. (This bag can't be used any more). Then he starts collecting the treasures in a new bag.
The cost of the bag is directly proportional to the weight it can hold, so try to reduce the cost.
Fortunately, Donn knows the weights of the treasure in each stage, help Donn choose his bag.
Example:
Consider there are 3 stages (n = 3) in the Hunt. The weight of the treasures in each of these stages (which are known to Donn before the hunt starts) are 1, 2 and 3. Donn is allowed to get 2 bags (k = 2) in this example.
n = 3, k= 2
stages = {1, 2, 3}
Donn could accomplish his target if each of his bag can accommodate 3 kg or 5 kg.
Explanation:
If the weight of the bag is 3 - Stage 1 weight + stage 2 weight = 1+2 = 3 <= 3 in one bag, stage 3 weight = 3 <= 3 in another bag. Thus they fit in the bags
If the weight of the bag is 5 - Stage 1 weight = 1 <= 5 in one bag, stage 2 + stage 3 weight = 2+3 = 5 <= 5 in another bag. Thus they fit in the bags but consider a bag size of 2:
1 + 2 > 2 so put stage 1 treasure alone in 1st bag
2 + 3 > 2 so put stage 2 treasure alone in 2nd bag
Now we need one more bag to put in the 3rd treasure.
This is not possible so you can't choose a bag of size 2, and a bag of size >= 3 can be used. Donn is intelligent and so he wants to pay the minimum cost so Donn will purchase a bag of size 3. Help Donn solve his problem.
Input:
0 < T <= 100, number of test cases.
Each test case contains:
0 < N <= 1000, number of stages and then a space followed by 0 < k <= 1000, number of bags allowed.
the next N lines contains the weights of the treasures in each stage. The weight of the treasure <= 1000.
Output:
Output a single line containing the minimum size of the bag needed.
Example
Input:
1
3 2
1
2
3
output:
3 | 33,371 |
PLAY WITH MATH (ENIGMATH)
You would have been fed up with competitive programming questions so far, now it is time to solve little math.
Assume you have a equation A × x - B × y = 0
For a given value of
A
and
B
, find the minimum positive integer value of
x
and
y
that satisfies this equation.
Input
First line contains
T
, number of test cases 0 ≤
T
≤1000 followed by
T
lines.
First line of each test case contains two space separated integers
A
and
B
. 1 ≤
A
,
B
≤1 000 000 000.
Output
For each test case, output a single line containing two integers
x
and
y
(separated by a single space).
Example
Input:
1
2 3
Output:
3 2
Note:
Brute force won't pass the given constraint.
Negative number cases are avoided to make the problem easy. | 33,372 |
Ascending Fibonacci Numbers (ASCDFIB)
John is trying to learn the Fibonacci sequence. This is what he has learned so far. The first two terms of the sequence are f(1) = 0 and f(2) = 1. The next term f(n) is then calculated by adding the previous two terms f(n-1) and f(n-2). Therefore,
f(1) = 0
f(2) = 1
f(3) = f(2) + f(1) = 1 + 0 = 1
f(4) = f(3) + f(2) = 1 + 1 = 2
f(5) = f(4) + f(3) = 2 + 1 = 3
f(6) = f(5) + f(4) = 3 + 2 = 5
After calculating this for a while, John realized that the values are becoming too big. In order to keep the values small, John changed his algorithm. Instead of calculating f(n) = f(n-1)+f(n-2), he decided he will calculate f(n) = ( f(n-1)+f(n-2) ) % 10^5.
Now John wants to do some research on his new modified Fibonacci sequence. He will give you an integer A (A<=10^5) and an integer B (B<=10^6). You have to output all the terms from f(A) to f(A+B) in ascending order (non-decreasing order). But printing so many numbers is too much of a hassle. So, if there are more than 100 terms in the output, then only print the first 100.
Input
The first line contains an integer
T
(
T
<=100), which is the number of test cases.
Each test case contains two positive integers
A
and
B
as mentioned before.
Output
For each test case, print case number (Check sample output) and then print the terms from f(A) to f(A+B) in ascending order (non-decreasing order). If there are more than 100 terms in the output, then only print the first 100.
Example
Input:
3
1 3
3 3
100 1
Output:
Case 1: 0 1 1 2
Case 2: 1 2 3 5
Case 3: 15075 69026 | 33,373 |
Boxes of Chocolate (BOXSCHOC)
Choco-moo has gone to the super market to buy chocolates for his friends. He entered a shop and found that they sell many boxes of chocolates. All the chocolate boxes are lined up on the display and there are exactly
N (0 < N <= 100000)
chocolate boxes. The i-th number box contains
A
i
(0 < Ai <= 100000)
amount of chocolates inside. Choco-moo loves chocolates and wants to buy all of the boxes, but he won’t. He will only buy boxes that contains amount of chocolates that can be divided by
K
(0 < K <= 100000)
since he has K number of friends and wants to divide the chocolates equally without wasting any chocolates.
Now, you are given the value N and then N numbers indicating the amount of chocolates inside the N boxes. You have to answer some queries for Choco-moo. You will be given
Q
(0 < Q <= 100000)
queries.
In each query, Choco-moo will provide you with three integers,
A
,
B
(0 < A<=B <= N)
and K. Here A and B are index number and K is the number of friends Choco-moo has. Now you have to find how many chocolate boxes Choco-moo can buy between Ath box to Bth box (inclusive)?
Input
The first line contains an integer
T
(
T
<=2), which is the number of test cases.
Each test case starts with a number
N.
After that N positive numbers follow indicating amount of chocolates inside each box. After that an integer
Q
is provided indicating number of queries to be answered. Each query has three integers, A, B and K. The ranges of the variables are described in the description.
Output
For each test case, print case number (Check sample output) and then for every query print the number of chocolate box Choco-moo can buy for his K friends from Ath box to Bth box (inclusive) in a newline.
Example
Input:
2
5
1 2 3 4 5
2
1 5 1
1 5 2
5
12 32 5 12 9
3
1 5 2
3 5 3
2 5 2
Output:
Case 1:
5
2
Case 2:
3
2
2
Explanation
: In Case 1: Query 1 Choco-moo buys all the boxes since all boxes are divisible by 1. In query 2 he buys second and fourth box since they are divisible by 2 ( 2 and 4 ).
Note:
Let me know if you think the judge data is weak or there is ambigutiy/mistake in the problem statment. | 33,374 |
Self Numbers (MCUR98)
Background
In 1949 the Indian mathematician D.R. Kaprekar discovered a class of numbers called
self-numbers
. For any positive integer
n
, define
d(n)
to be
n
plus the sum of the digits of
n
. (The
d
stands for
digitadition
, a term coined by Kaprekar.) For example:
d(75) = 75 + 7 + 5 = 87
Given any positive integer n as a starting point, you can construct the infinite increasing sequence of integers
n, d(n), d(d(n)), d(d(d(n))), ...
For example, if you start with 33, the next number is 33 + 3 + 3 = 39, the next is 39 + 3 + 9 = 51, the next is 51 + 5 + 1 = 57, and so you generate the sequence
33, 39, 51, 57, 69, 84, 96, 111, 114, 120, 123, 129, 141, ...
The number
n
is called a
generator
of
d(n)
. In the sequence above, 33 is a generator of 39, 39 is a generator of 51, 51 is a generator of 57, and so on.
Some numbers have more than one generator: For example, 101 has two generators, 91 and 100. A number with no generators is a
self-number
. There are thirteen self-numbers less than 100: 1, 3, 5, 7, 9, 20, 31, 42, 53, 64, 75, 86, and 97.
Problem
Write a program to output all positive self-numbers less than 1000000 in increasing order, one per line.
Input
There is no input.
Output
All positive self-numbers less than 1000000 in increasing order, one per line. | 33,375 |
Number Magic II (SNGNM2)
num (> 9) be a positive integer. sum is defined as sum_of_digits_of_num. avg is defined as
sum / digits_in_num
and avg takes only integer values (for example 34 / 5 is equal to 6, i.e. integer part of 6.8).
Now digits of num are rearranged by taking avg as pivoting element. Rearrangement is done according the following method:
[step 1]
new_num = avg;
read digits of num
if (digit > avg)
place digit at rightmost place in new_num
else
place digit at leftmost place in new_num
[step 2]
new_num is again rearranged into two numbers, eve_number (
formed by taking digits of new_num at places 2, 4, 6, ...
) and odd_number (
formed by taking digits of new_num at places 1, 3, 5, ...
).
Remember that counting of digit place starts from left-most digits as 1, 2, 3, 4...
[step 3]
if (eve_number has < 3 digits)
store the number
else
calculate avg and again start from process 1
if (odd_number has < 3 digits)
store the number
else
calculate avg and again start from step 1
Finally all desired numbers are stored and now we have to find two magical coefficients of num, named as alpha and beta.
[method digit_sum]
number = num
do {
number = sum of digits of number
} while (number >= 10)
dig_sum = number
[alpha]
digit_sum(summation_of_stored_numbers)
[beta]
digit_sum(summation_of_digit_sum(stored_numbers))
we will say num is magic number if alpha, beta and |aplha - beta| are digits of num.
Input
First line of input is t (< 101), number of test cases. Each test case has n (< 501) as its first input and next n lines contains num (< 10
101
).
Output
For each test case, write exactly n lines containing value of alpha and beta; and yes or no according to whether or not num is magic number.
Example
Input:
1
1
9874
Output:
5 5 no
Explanation
num = 9874
avg = 7 (28 / 4)
rearrangement of num generates new_num = 47798.
thus eve_num = 79 and odd_num = 478.
now eve_num < 100, so 79 is stored.
but odd_num >= 100 so repeat the full process.
Finally stored numbers are N[] = 79, 68 and 47.
Make sure that you have to consider the total number of digits not the value of the number so
you should not change the total number of digits of the number at any step
. | 33,376 |
The Triangle Game (MCU20A)
In the triangle game you start off with six triangles numbered on each edge, as in the example above. You can slide and rotate the triangles so they form a hexagon, but the hexagon is only legal if edges common to two triangles have the same number on them. You may not flip any triangle over. Two legal hexagons formed from the six triangles are illustrated below.
The score for a legal hexagon is the sum of the numbers on the outside six edges.
Your problem is to find the highest score that can be achieved with any six particular triangles.
The input file will contain one or more data sets. Each data set is a sequence of six lines with three integers from 1 to 100 separated by blanks on each line. Each line contains the numbers on the triangles in clockwise order. Data sets are separated by a line containing only an asterisk. The last data set is followed by a line containing only a dollar sign.
For each input data set, the output is a line containing only the word "none" if there are no legal hexagons or the highest score if there is a legal hexagon.
Example
Input:
1 4 20
3 1 5
50 2 3
5 2 7
7 5 20
4 7 50
*
10 1 20
20 2 30
30 3 40
40 4 50
50 5 60
60 6 10
*
10 1 20
20 2 30
30 3 40
40 4 50
50 5 60
10 6 60
$
Output:
152
21
none | 33,377 |
Edge Detection (MCU20E)
IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges.
A simple edge detection algorithm sets an output pixel's value to be the maximum absolute value of the differences between it and all its surrounding pixels in the input image. Consider the input image below:
The upper left pixel in the output image is the maximum of the values |15-15|, |15-100|, and |15-100|, which is 85. The pixel in the 4th row, 2nd column is computed as the maximum of |175-100|, |175-100|, |175-100|, |175-175|, |175-25|, |175-175|, |175-175|, and |175-25|, which is 150.
Images contain 2 to 1,000,000,000 (10
9
) pixels. All images are encoded using run length encoding (RLE). This is a sequence of pairs, containing pixel value (0-255) and run length (1-10
9
). Input images have at most 1,000 of these pairs. Successive pairs have different pixel values. All lines in an image contain the same number of pixels.
Input
Input consists of information for one or more images. Each image starts with the width, in pixels, of each image line. This is followed by the RLE pairs, one pair per line. A line with 0 0 indicates the end of the data for that image. An image width of 0 indicates there are no more images to process. The first image in the example input encodes the 5x7 input image above.
Output
Output is a series of edge-detected images, in the same format as the input images, except that there may be more than 1,000 RLE pairs.
Important Note
: A brute force solution that attempts to compute an output value for every individual pixel will likely fail due to space or time constraints.
Sample
Input:
7
15 4
100 15
25 2
175 2
25 5
175 2
25 5
0 0
10
35 500000000
200 500000000
0 0
3
255 1
10 1
255 2
10 1
255 2
10 1
255 1
0 0
0
Output:
7
85 5
0 2
85 5
75 10
150 2
75 3
0 2
150 2
0 4
0 0
10
0 499999990
165 20
0 499999990
0 0
3
245 9
0 0
0 | 33,378 |
Psycho (PSYCHON)
Given an integer N, the number N is called “
Psycho Number
”. Psycho Number is calculated as follows:
First, If we factorize N , then we have some prime and their power. Assume that, there are M powers. From M powers , you should count the number of even and odd powers. Then if the number of even power is strictly greater than odd power, then we call the number N is “
Psycho Number
”, otherwise the number N is call “
Ordinary Number
”.
As for example, if N = 67500 then prime factorization,
67500 = 2
2
x 3
3
x 5
4
.
Count even powers and odd powers . This number have 2 even power(2, 4) and 1 odd power (3). Since even power 2 (2, 4) is greater than odd power 1 (3), so the number 67500 is a Psycho Number.
Input:
An integer
T
(1 <=
T
<= 10
6
) denoting the number of test cases followed by T lines. Each containing a single integer
N
(1 <=
N
<= 10
7
).
Output:
For each case print “
Psycho Number
” or “
Ordinary Number
”.
Sample
Sample Input
2
3
4
Sample Output
Ordinary Number
Psycho Number
Note: 0 and 1 are not a psycho number.
Psycho 2:
Psycho Function
Psycho 3:
Make Psycho
Psycho 4:
Psycho34 (easy)
Problem setter:
Shipu Ahamed, Dept. of CSE,
Bangladesh University of Business and Technology (BUBT)
[ Edited by EB ]
Warning:
Some input files are broken. | 33,379 |
Tip Top Game (TIPTOP)
Alim and Sufian are two good friends. They love playing a game with numbers, and recently, they discovered a new game called “Tip Top”. The rule of the game is they took a number (
N
) randomly, after that they find all divisors of N. Then they starting to play the game first Alim took a divisor, then Sufian so on. The person who took the last divisor will win the game.
Every time the game started with Alim. Now Alim wants to know when he will win.
As you a good programmer your task is to find will Alim win or not.
Input
Input starts with an integer
T (T ≤ 10
5
)
, denoting the number of test cases. Each case starts with a line containing an integer
N
(1 ≤ N ≤ 10
18
)
the number.
Output
For each case you have to print “
Yes
” if Alim will win otherwise “
No
” with case number. See the sample for exact formatting.
Sample
Input:
2
4
5
Output:
Case 1: Yes
Case 2: No
Problem setter: Ajharul Islam Barid, Dept. of CSE
Bangladesh University of Business and Technology (BUBT) | 33,380 |
Minimum Number (MINNUM)
Prana has given a number. Now she wonder what will be the maximum number of digits that the sum of these digits is equal to the given number. After thinking sometimes she laughed at herself, cause the number is infinite.
Now your task is to find the minimum number of digits that the sum of these digits is equal to the given number.
Input
The input contain a single integer
N
(0 ≤
N
≤ 10
31
). The input is terminated by a line containing
-1
.
Output
Output a single line the number of digits that the sum of the digits is equals to the given number. See the sample input/output for exact formatting.
Sample
Input
11
1
-1
Output
2
1
Explanation
For the first test case given number is 11. Some possible way to make 11 is
7+4=11 which costs 2 digits.
2+3+6=11 which costs 3 digits.
1+2+3+5=11 which costs 4 digits.
1+2+3+0+5=11 which costs 5 digits.
So, here first example costs the minimum number of digits which is 2.
Note: There are no extra new lines between different numbers.
Problem setter: Abu Sufian, Dept. of CSE,
Bangladesh University of Business and Technology (BUBT) | 33,381 |
Fone Frequencies (OU7)
When relay towers for mobile telephones communicate with the mobile phones in their area, there is
always the possibility of interference. So, when assigning the transmission frequency, the FCC makes
sure that nearby towers have frequencies that aren't too close. On the other hand, the FCC does not
want to assign too many different frequencies; they want to save as many as possible for other uses.
Your job is to find an optimal assignment of frequencies.
In this problem, the frequencies will be integers. Nearby towers must be assigned frequencies that differ
by at least 2. You'll find an assignment using as few frequencies as possible. For example, consider the
following two arrangements of towers. Two towers near each other are indicated by the connecting line.
Note that the following are legal frequency assignments to these two tower configurations. However,
the second arrangement does not use the fewest number of frequencies possible, since the tower with
frequency 5 could have frequency 1.
Input
There will be multiple test cases. Input for each test case will consist of two lines: the first line will
contain the integer n, indicating the number of towers. The next line will be of the form x1 y1 x2 y2 ...
xn yn where xi yi are the coordinates of tower i. A pair of towers are considered "near" each other
if the distance between them is no more than 20. There will be no more than 12 towers and no tower
will have more than 4 towers near it. A value of n = 0 indicates end of input.
Output
For each test case, you should print one line in the format:
The towers in case n can be covered in f frequencies.
where you determine the value for f. The case numbers, n, will start at 1.
Example
Input:
5
0 0 5 7.5 1 -3 10.75 -20.1 12.01 -22
6
0 1 19 0 38 1 38 21 19 22 0 21
0
Output:
The towers in case 1 can be covered in 3 frequencies.
The towers in case 2 can be covered in 2 frequencies. | 33,382 |
Help Professor (HPPROF)
One day, TA of one of the course at DA-IICT was checking First In-sem exam papers. The exam was of 20 marks. After checking some of the papers, he decided to give marks of those students to his professor but he messed up here. He forgot to put spaces between the marks. So professor got confused.
Since you are his favourite student, help him determine the number of ways in which this marks can be separated (by spaces) so that they are valid marks.
Marks are valid if they are between 0 to 20 and have no leading zeros. For example, 0, 1, 2, 3 ... 20 are valid but 01, 003, 21, 25 are not valid.
Input
Input contains only one line, a string of length less than 20 .
Output
Output the number of ways in which you can put spaces and interpret them as a valid marks of students.
Example
Input 1:
12
Output 1:
2
Input 2:
111
Output 2:
3
Input 3:
101
Output 3:
2
Explanation:
In the first case, 12 can be interpreted in two ways,
1, 2
12
In the second case, 111 can be interpreted as following ways.
1, 1, 1
11, 1
1, 11
In the third case,
1, 0, 1
10, 1
Note that 1, 01 can not be valid because 01 has leading zeros. | 33,383 |
Help Rarity Collect Crystals (PONY9)
Rarity is collecting special crystals for the upcoming Equestria games. Currently, she is in a gem cave and has found a bunch of crystals.
To Rarity's discerning eye, crystals have three properties: a color, a reactivity level, and a fashion value.
Of course, Rarity wants to collect crystals to maximize the total fashion value.
Rarity knew she wouldn't have enough room in just one bag for all the crystals, so she brought two.
Well, it turns out that space isn't the main issue that Rarity has. These special crystals are reactive.
In their current environment, they are relatively stable, but once Rarity has put them in her bag and
taken them out of the gem cave, if the reactivity levels are too high, the gems will disintegrate, and thus lose all their fashion value.
There are two ways that reactions can happen:
If there are too many gems of the same color, in the same bag, they'll disintegrate.
If the total reactivity level of the crystals in the same bag is too high, they'll disintegrate.
Different colors of gems have different reaction limits. Also, it is possible that some colors of gems are simply unstable and will always disintegrate when taken outside the cave.
Twilight Sparkle had studied these crystals at some point, and discovered a way to stop crystals from reacting. The material is difficult to create, but she has still given Rarity a separate, special bag which can hold only a single crystal, but that crystal won't react no matter what while it is in the bag.
This is the situation Rarity is in, and she needs your help.
Input
You will be given T, the number of test cases to follow.
Each test case begins with a single line containing the values R and C:
R is the maximum reactivity level allowed in a regular bag without having the crystals disintegrate.
C is the number of different colors of gems that Rarity currently can see.
The next C lines will be of the form L N r
1
v
1
r
2
v
2
... r
N
v
N
.
L is the limit for how many crystals of this color can be in the same bag without reacting.
N is the number of crystals of this color that Rarity can see.
The next 2×N numbers are pairs indicating the reactivity level and the fashion value of each of the N gems.
Test cases will follow immediately after each other (see sample input)
Limits:
1 ≤ R ≤ 100
1 ≤ C ≤ 10
0 ≤ L ≤ 3
1 ≤ N ≤ 10
For any reactivity level 'r' or fashion value 'v', 1 ≤ r, v ≤ 1000
Note that Rarity's two regular bags are large enough to hold any number of crystals.
Output
For each test case, on a separate line, output the maximum fashion value of the crystals that Rarity is able to collect
in her bags.
Example
Input:
2
10 2
1 2 5 1 5 1
2 2 6 1 6 1
5 3
3 3 1 1 1 1 1 1
3 3 1 1 1 1 1 1
3 3 1 1 1 1 1 1
Output:
3
9
Final note: The time limit for each test case is at a minimum, 3× my Java solution. There are a few files with the input being 1-2MB. | 33,384 |
Count Primes (SNGCP)
Let
num(num >= 0)
is a positive integer or zero. We can represent num in the following two forms if it is possible to do so -
1.
num = n
2
+ 2 * n, for non-negative integer n
2.
num = m
2
- 2 * m,
for non-negative integer m
Suppose there is
num
that can be represented in both the forms. Consider this type of number as a magic number. Consider the following 5 cases -
1. n is the only prime.
2. m is the only prime.
3. n and m both are primes.
4. n is prime.
5. m is prime.
Input
First line of input is t, total number of test cases. For each test case the first line is q, total number of queries. Then there will be (2 * q) lines. First line contains c (referring to case mentioned in the problem description) and second line contains two integers a and b defining the range
[a, b]
for magic number.
t < 1001
q < 5001
0 < c < 6
minimum_value_of_a = 0
maximum_value_of_b = 10
6
Output
For every test case, that has q queries, the output has (q + 1) lines. First line will be simply printing the test case number and then q lines will be printing total number of magic numbers in the given range [a, b] under the specific case mentioned in input.
Example
Input:
2
3
1
5 20
2
1 30
3
10 18
2
4
1 10
5
1 10
Output:
Test Case :#1:
Query :#1: 1
Query :#2: 1
Query :#3: 1
Test Case :#2:
Query :#1: 1
Query :#2: 1 | 33,385 |
Hackers (TREEBA)
Hackers are eavesdropping communication between Mirko and Slavko and trying to understand the intercepted messages.
Dictionary from Mirko and Slavko contains M words and every message which one of them send to another consists of a series of words from dictionary separated by spaces.
However, the messages which hackers are intercepting due to poor quality of their equipment are changed as follows:
In the message are inserted at most K noises - arbitrary strings of letters. Every noise is always inserted between two words or before the first or after the last word and never within a word.
All spaces between the words in the message are deleted.
For example, if Mirko sends a message 'mirko slavko', when hackers intercept it, it can be 'mirkoxyzslavko', where 'xyz' is a noise, and the words 'mirko' and 'slavko' are found in the dictionary.
Hackers know their dictionary and have just received a new altered message which they want to disassemble to the dictionary words and sounds. Of all possible ways in which they can do that, they are interested in the one which has the most words from the dictionary.
Write a program that, given the dictionary, the number K, and received a modified message obtained as described above, determines a way in which the most words from dictionary are used.
Input
The first line contains number T (1 ≤ T ≤ 12) - the number of test cases.
The second line contains two integers M (1 ≤ M ≤ 1000) and K (0 ≤ K ≤ 10) - the number of words in the dictionary and the maximum amount of noise in each received message.
The third line is the text messages received - a series of lowercase letters of length N (1 ≤ N ≤ 10 000). Each of the following M lines contains a word in the dictionary - a series of at least one and a maximum of 20 lowercase letters.
Output
In the first line of output write maximum number of words from the dictionary in disassembled message.
Example
Input:
1
5 3
prisluskujuabcdnassumhakeri
mirko
nas
slavko
hakeri
prisluskuju
Output:
3
Explanation
: One of the messages is 'prisluskuju #### nas ### hakeri' which has two noises, and maximum of three words. | 33,386 |
Can you play carrom !!! (CARRHIM)
Carrom board is a very popular game. There are four player in this game in dual player mode. In dual player game the team is pair with opposite side player.
So, in picture you see the board and the players. Where the player A and the player C in team-1, the player B and the player D in team-2.
In this game a team is play with one color pawn. So, if team-1 start playing the board they take the white pawn, and the team-2 get the black pawn for the game. If team-1 can cover all the pawn before the team-2 and the red also covered by the time then the team-1 will win. Otherwise team-2 will win if they cover their all pawn in the game.
Now, There are 9 white pawn and 9 black pawn and one red pawn in the board. The game is played by different rule.
In my problem of this game the rule like,
The point for the one pawn is 1 and for red is 5.
You can assume that which player 1st start playing the game is start with the white pawn.one team must cover red pawn and this team will get the red point. And you know the penalty rule is If one player cover one pawn of opposite team then the turn goes to the next player.
Now your task is to find the winner team and points.
The points count by the remaining of pawn in the board and plus the covered red pawn point by the winning team.
Input
Input consists of pairs of lines (at most 100 lines). Each pair contains 1 character and 3 integer. A first character is the player id (A , B , C or D) and three integer is W, B, R (1 <= W, B <= 9) separated by a space that is number of white, black and red pawn the player cover in his turn. The end of one input occurs when the first sequence starts with an "#" character (without the quotes).
Output
For each case if the game complete then you have to print a string “Team-1 win and the point is N.” (without the quotes) when team-1 win , Otherwise “Team-2 win and the point is N.” (without the quotes).
If the game is incomplete then print a string "Incomplete game." (without the quotes) when a team can not cover all the pawn of his turn.
N is the total point of winner team. See the sample input/output for exact formatting.
Sample
Input :
A 5 1 0
B 1 2 0
C 2 1 1
D 1 0 0
#
B 1 1 0
C 1 2 0
D 3 1 1
A 1 2 0
B 3 0 0
#
A 1 1 0
B 1 5 1
C 1 1 0
#
Output :
Team-1 win and the point is 10.
Team-2 win and the point is 8.
Incomplete game.
Explanation :
For the first input player A start the game so the team-1 play with the white pawn.
After all input the team-1 cover all of white pawn also the red pawn.
and there are 5 black pawn remain in the board.
so, team-1 win and the point is 5+5=10.
____________________________________________________________________________________________________________
Problem setter
: Md. Hashibul Amin Hemel, Dept. of CSE
Bangladesh University of Business and Technology (BUBT) | 33,387 |
MODIFY SEQUENCE (NITK06)
Suppose we have a sequence of non-negative integers, Namely a
1
, a
2
... a
n
.
At each time we can choose one term a
i
with 0 < i < n and we subtract 1 from both a
i
and a
i+1
.
We wonder whether we can get a sequence of all zeros after several operations.
Input
The first line is the number of test cases T (0 < T ≤ 20).
The first line of each test case is a number N (0 < N ≤ 10000). The next line is N non-negative integers, 0 ≤ a
i
≤ 10
9
.
Output
If it can be modified into all zeros with several operations output
“YES”
in a single line, otherwise output
“NO”
instead.
Example
Input:
2
2
1 2
2
2 2
Output:
NO
YES
Explanation
It is clear that [1 2] can be reduced to [0 1] but no further to convert all integers to 0. Hence, the output is NO.
In second case, output is YES as [2 2] can be reduced to [1 1] and then to [0 0] in just two steps. | 33,388 |
THE INDIAN OCEAN (NITK07)
Salim is a part of THE INDIAN OCEAN BAND. Each musician of the band has already decided what sound will he play (for the sake of simplicity we assume each musician plays only one sound). We say two sounds are in harmony if the frequency of any one of them divides the frequency of the other (that's a pretty restrictive idea of harmony, but THE INDIAN OCEANS are known to be very conservative in music). Salim knows that the notes played by other players are not necessarily in harmony with each other. He wants his own note to improve the music, so he wants to choose his note so that it is in harmony with the notes all the other musicians play.
Now, this sounds simple (as all the frequencies are positive integers, it would be enough for Salim to play the note with frequency 1, or, from the other side, the Least Common Multiple of all the other notes), but unfortunately Salim's instrument has only a limited range of notes available. Help Salim find out if playing a note harmonious with all others is possible.
Input
The first line of the input gives the number of test cases,
T
.
T
test cases follow. Each test case is described by two lines. The first contains three numbers:
N
,
L
and
H
, denoting the number of other players, the lowest and the highest note Salim's instrument can play respectively. The second line contains
N
integers denoting the frequencies of notes played by the other players.
1 ≤
T
≤ 40.
1 ≤
N
≤ 10
4
.
1 ≤
L
≤
H
≤ 10
16
.
All the frequencies are no larger than 10
16
.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is either the string "NO" (if Salim cannot play an appropriate note), or a possible frequency. If there are multiple frequencies Salim could play, output the lowest one.
Example
Input:
3
3 2 100
3 5 7
4 8 16
1 20 5 2
2 5 10000000000000000
9999999999999606 9999999999999822
Output:
Case #1: NO
Case #2: 10
Case #3: 6 | 33,389 |
Save the cows! (COD1)
There is a green square grid of size n×m with k cows in it.
The objective of the cows is to escape the field. If any one of the cows escape all cows are set free.
There is a farmer who tries to restrict the field by putting up fences along the border. Initially the grid is not fenced.
Cows coordinate and think of a plan to escape. Cows get the first move. Cows and farmer move alternatively. At any move any one of the k cows can move to their neighboring cell (the cell that shares an edge with it). If the cow is already at the edge of the field and the edge is not fenced then it can escape it and hence all cows are set free. After every move of the cows the farmer can fence some edge at the border of the field of length 1 so that no cow is able to escape from that edge anymore.
The question is: "Will the innocent cows manage to escape?"
Input
First line contains T-number of test cases (0 < T ≤ 100.)
Each test case contains 3 integers, separated by space: 1 ≤ n, m ≤ 100 — dimensions of the field and 0 ≤ k ≤ 100 — the number of cows. Each of the next k lines contains 2 integers, separated by space: 1 ≤ x ≤ n, 1 ≤ y ≤ m — coordinates of the corresponding cow. There could be more than one cow at a cell.
Output
Output one word: "YES" — if cows escape, "NO" — otherwise.
Example
Input:
1
2 2 1
1 2
Output:
YES | 33,390 |
Deconnecting (CODGRF)
We define a Beta graph as a set of nodes connected by edges such that one node is connected to another node by at most one edge and no node has an edge starting and ending on itself. Each node has a finite number called 'degree' associated with it which is the number of edges connecting that node to the rest of the nodes.
There are n nodes in a given Beta graph. Those nodes with degree=0 are removed from the graph. Then those, who had degree=1 were removed (and so are the edges connecting that node to the rest of the nodes). Then those, who had degree equal to 2, 3 ... n-1 were removed (including their edges).
For any Beta graph with n nodes find the maximum number of nodes that can remain after the above procedure is completed.
Input
The first input line contains one number t — amount of tests (1 ≤ t ≤ 10^5). Each of the following t lines contains one integer number n (0 ≤ n ≤ 10^5).
Output
For each test case output in a separate line the maximum number of nodes that can remain after the above procedure is completed.
Example
Input:
1
3
Output:
1 | 33,391 |
Naya Shatranj (New Chess) (CODCHESS)
A and B are playing a very interesting variant of the ancient Indian game 'shatranj' (also known as chess) on a 'maidaan' (chessboard) n×n in size.
They take turns to put game pieces called 'ghoda'(knight) so that no two 'ghodas' (knights) could threaten each other.
A 'ghoda' located in square (a, b) can threaten squares (a + 1, b + 2), (a - 1, b + 2), (a + 1, b - 2), (a - 1, b - 2), (a + 2, b - 1), (a + 2, b + 1), (a - 2, b - 1), (a - 2, b + 1).
The player who can't put a new 'ghoda' during his move loses. Find out which player wins considering that both players play optimally well and A starts.
Input
The first line contains integer T (1≤T≤10^4) — the number of 'maidaans' (boards), for which you should determine the winning player. Next T lines contain T integers ni (1 ≤ ni ≤ 10^5) — the sizes of the 'maidaans' (chessboards).
Output
For each ni×ni board print on a single line "0" if A wins considering both players play optimally well. Otherwise, print "1".
Example
Input:
2
2
1
Output:
1
0 | 33,392 |
Hashcodes and primes (CODHASH)
There are n cards arranged in a row. The rth card from the left has rth prime number written on it on one side the other side is blank. Some cards have the blank side up and the others have the number side up.
Cards with their blank side up are known as 0-cards and cards showing the prime numbers are known as 1-cards.
A hash code is generated from the set of cards in the following way:
Initial value of hashcode is 1.
All the 0-cards should be turned upside down to convert them to a 1-card in order to get the final value of the hash code.
At each step a 0-card can be turned upside down if there's at least one 1-card adjacent to it. Once the card is turned the value of the hash code is changed according to the following equation:
New value of hashcode = (Previous value of hashcode) * ((Number on the card)^(Number of 0-cards left on the table+1))
Once all the cards on the table are 1-cards we get the final value of hash code.
Find the total number of distinct hash codes that can be generated like this for the given arrangement of cards.
Input
The first line contains 0 < T ≤ 1000 the number of test cases.
The first line of every test case contains two integers n and m where n is the number of cards on the table and m is the number of 1-cards on the table, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of the cards that are 1-cards.
Output
For every test case print in a separate line the number of distinct hash codes that can be generated for the given arrangement of cards modulo 1000000007 (10
9
+ 7).
Example
Input:
2
3 1
1
4 2
1 4
Output:
1
2 | 33,393 |
Change (TPC07)
How many ways are there to pay
n
cents? We assume that the payment must be made with pennies (1 cent), nickels (5 cents), dimes (10 cents), quarters (25 cents), and half-dollars (50 cents).
For example, there are four ways to pay 13 cents, namely (13 pennies), (2 nickels, 3 pennies), (1 nickel, 8 pennies), and (1 dime, 3 pennies).
Input
The input will contain multiple test cases. Each test case contains a single line with a single integer
n
(1 ≤
n
≤ 1000000000).
The input will be terminated by the end of file.
Output
For each input integer
n
, output how many ways are there to pay
n
cents in a single line.
Sample Input
13
100000000
Sample Output
4
66666793333412666685000001 | 33,394 |
Platinum Relic! (PTRELIC)
Samuel has found a copy of a classic videogame called Crash Bandicoot!
Crash Bandicoot is a platform adventure videogame on which the player must complete levels by destroying crates and beating enemies. After completing successfully a level, the player is awarded with some prizes, such as crystals, gems and relics.
Samuel has already obtained all the crystal and gems of the game, and now he is aiming for the relics. A relic is obtained after completing successfully a Time-Trial challenge on a level.
However, Samuel knows there are two kinds of relics: Sapphire and Gold. Gold relics are harder to obtain than the sapphire ones, giving that the challenge must be completed going even faster.
When you start a Relic Challenge, the game tells you the maximum time you can expend in the level in order to obtain the sapphire relic, and after obtaining it, it tells you the gold relic time.
And Samuel has found a third hidden kind of relic even harder to obtain, the platinum relic! He wants to complete every challenge with this prize. However, Samuel doesn’t like to guess the time limit to obtain the platinum relic, so he hired you to find it quickly.
Your program must give the game a time in format hh:mm:ss:mss (hours, minutes, seconds and milliseconds respectively), where all the numbers, except hh, must have leading zeros. (By printing it in STDOUT)
Examples:
0:04:57:987
2:14:08:057
Once you submit a time, the game will answer you with the relic you will win if you beat the level with that time.
For example, if the Relic challenges are:
Sapphire: 0:02:00:000
Gold: 0:01:35:000
Platinum: 0:01:00:000
And you submit 0:01:15:000, the game will answer "GOLD". If you submit 0:02:00:000 you will get "SAPPHIRE" and if you submit a time which surpass all the time limits, you will get "NO RELIC" as an answer.
When you have the answer, you must print "PLATINUM:", followed by a blank space, and then the maximum time Samuel can expend in order to obtain a platinum relic.
Some levels are absurdly long, so you must not make any assumption of how long a level can be.
Input
You will only receive the Sapphire time limit in the format explained above.
Run Example
Game
: 0:02:00:000
You
: 0:01:45:000
Game
: SAPPHIRE
You
: 0:01:15:000
Game
: GOLD
You
: 0:00:45:567
Game
: PLATINUM
You
: 0:01:00:000
Game
: PLATINUM
You
: PLATINUM: 0:01:00:000
NOTE: the program should clear the output buffer after printing each line. It can be done using
fflush(stdout)
command or by setting the proper type of buffering at the beginning of the execution -
setlinebuf(stdout)
. | 33,395 |
Ratar (RATAR)
After Mirko's failed stint as a coach and a passing obsession with Croatian meat delicacies, his weight
problems have motivated him to work hard as a farmer. He has moved to a village where his friend
Slavko lives. Farmers in the village share a large common plot of land in the shape of a N×N square,
divided into N² unit squares. A unit square at coordinates (i, j) brings in the income of Aij, which can
be negative (for example, if the square has to be maintained but is not cultivated). The farmers always
divide the common land into smaller rectangular fields with edges parallel to the common land
edges.
Slavko is sceptical of Mirko since his failure as a coach, so he insists that both of them are assigned
land with the same total income, but also that the two plots share exactly one common corner so
that the two friends can keep an eye on each other (Slavko knows that Mirko is prone to mischief). The
common corner must be the only point where the two plots meet, in order to prevent border-related
arguments.
You are given a description of the common land plot. Find the total number of plot pairs that satisfy
Slavko's criteria.
Input
The first line of input contains the positive integer N (1 ≤ N ≤ 50), the dimensions of the common
land plot.
Each of the following N lines contains N space-separated numbers Aij (-1000 < Aij < 1000), the income
provided by the respective cell.
Output
The first and only line of output must contain the total number of plot pairs satisfying the given
condition.
Example
Input:
3
1 2 3
2 3 4
3 4 8
Output:
7 | 33,396 |
Megatron and his rage (CODFURY)
Infuriated by the Decepticons' defeat after a long epic battle with the Autobots, Megatron, in his rage, has decided to destroy all the planets on his way back to Cybertron from Earth. There are multiple planets between Earth and Cybertron, and each planet has some number of Autobots to guard it from him. Since Megatron is low on ammo, he wants to fight as few Autobots as possible on his way back. He can defeat no more than "M" Autobots in total.
You need to find the maximum number of planets he can possibly destroy in his journey.
NOTE: Megatron can start his "destruction spree" from any planet, and can only move to the next planet from the planet he's currently on.
Input
You will receive one integer "T" denoting the number of test cases. (T <= 20)
Then, the next line will contain two non-negative space-separated integers "P" and "M", where P is the number of planets on his way back (P <= 50000) and M is the maximum number of Autobots that Megatron can see (M <= 1000,000).
After that, one line containing P integers separated by a single space will denote the number of Autobots present in each planet. (For each planet there will be no more than 1000 Autobots).
Output
Your output should consist of "T" pairs of space-separated integers, one pair per line, denoting the number of Autobots Megatron will fight and the number of planets he will destroy respectively.
Example
Input:
1
4 50
20 5 23 45
Output:
48 3
Explanation
Megatron starts at planet 1 (with 20 Autobots) and goes to planet 2, then the 3rd planet,
at this point, he has seen 48 Autobots, if he decides to go to planet 4 he will see 93 Autobots...
so he stops his journey at the 3rd planet.
Megatron, however, could have started at planet 2 with 5 Autobots, then continue up to the 4th planet, then,
he would have seen 73 Autobots, but, as he wants to see the minimum Autobots possible and
this number of Autobots exceeds what he wants to see, he decides to choose the way from the 1st to the 3rd planet. | 33,397 |
Mining your own business (BUSINESS)
John Digger is the owner of a large illudium phosdex mine. The mine is made up of a series of tunnels that meet at various large junctions. Unlike some owners, Digger actually cares about the welfare of his workers and has a concern about the layout of the mine. Specifically, he worries that there may a junction which, in case of collapse, will cut off workers in one section of the mine from other workers (illudium phosdex, as you know, is highly unstable). To counter this, he wants to install special escape shafts from the junctions to the surface. He could install one escape shaft at each junction, but Digger doesn't care about his workers that much. Instead, he wants to install the minimum number of escape shafts so that if any of the junctions collapses, all the workers who survive the junction collapse will have a path to the surface.
Write a program to calculate the minimum number of escape shafts and the total number of ways in which this minimum number of escape shafts can be installed.
Input
The input consists of several test cases. The first line of each case contains a positive integer
N
(
N
≤ 5x10
4
)
indicating the number of mine tunnels. Following this are
N
lines each containing two distinct integers
s
and
t
, where
s
and
t
are junction numbers. Junctions are numbered consecutively starting at 1. Each pair of junctions is joined by at most a single tunnel. Each set of mine tunnels forms one connected unit (that is, you can get from any one junction to any other).
The last test case is followed by a line containing a single zero.
Output
For each test case, display its case number followed by the minimum number of escape shafts needed for the system of mine tunnels and the total number of ways these escape shafts can be installed. You may assume that the result fits in a signed 64-bit integer.
Follow the format of the sample output.
Example
Input:
9
1 3
4 1
3 5
1 2
2 6
1 5
6 3
1 6
3 2
6
1 2
1 3
2 4
2 5
3 6
3 7
0
Output:
Case 1: 2 4
Case 2: 4 1 | 33,398 |
Football Fever (DCEPC11F)
Kapish is a huge fan of football. He loves anything and everything related to the game and never misses a single match when his favourite team, Manchester United, is playing. Being the coder that he is, one day he decides to create his own, slightly modified version of football, through code.
The game is played between 2 teams having
M players
each and continues for
N minutes
. In each minute of the game,
exactly one
of the following 5 events will take place:
Team 1 scores a goal
Team 2 scores a goal
A player from team 1 gets a red card
A player from team 2 gets a red card
None of the above
A player who gets a red card can take no further part in the game. If at any point of time, a team is left with less than 5 players on the field, it will automatically get disqualified, and the other team will be declared as the winner.
Kapish is very pleased with his new game. However, Pushap, who hates boring draws in football, is not impressed. “Do you even know how many ways are there for this game to end in a draw?” he asks.
Given N and M, can you help Kapish find out the number of ways for the game to end in a draw? (draw means both teams end up with the same number of goals at the end of N minutes) Since the number of ways can be very large, you need to print the answer mod 1000000007.
Note 1: Two ways are considered different, if the event(s) of at least 1 minute are different in them.
Note 2: For the sake of simplicity, you can assume that all the players in a team are identical.
Input
First line contains T, the number of test cases.
Each test case consists of a single line, with 2 space separated integers, N and M.
Output
For each test case, output a single line, containing the number of ways mod 1000000007.
Constraints
1 ≤ T ≤ 100
5 ≤ M ≤ 11
1 ≤ N ≤ 100
Example
Input:
2
1 11
2 8
Output:
3
11
Explanation
In the first test case, in the first minute, the occurrence of any of the events 3, 4 and 5 described in the problem can lead to a draw. Hence there are 3 ways for it to end in a draw. | 33,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.