task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Number Theory (NUMTRY)
f(n) and g(n) are two functions defined as following :
f(n) =
∏
(p
i
2e
i
+1
+1), where p
i
is prime factor of n and e
i
is highest power of p
i
in n.
g(n) =
Σ
(n / gcd(n, i)); 1 ≤ i ≤ n
For a given value of n, you have to compute [f(n) / g(n)] % 1000000007.
Input
First line has T (≤ 10000), next T lines has 2 ≤ n ≤ 10
12
.
Output
[f(n) / g(n)] % 1000000007 for each test case.
Example
Input:
2
2
4
Output:
3
3
Warning:
Test cases aren't random. Test files consist of large primes, strong pseudo primes, Carmichael numbers, squares of primes, product of large primes, worst possible test cases for fermat, miller rabin and other primality testing algorithms.
Note
: You may try the
tutorial version
( same test files, 5s-100s time limit ). | 32,800 |
GP - Complete the Series v1 () (GP1)
Geometric progression (GP) is a set in which the ratio of 2 consecutive numbers is same. for example: 1, 2, 4, 8, 16 - in this case, the ratio of the numbers is 2.
The task here is very simple indeed. You will be given the 3rd term, 3rd last term and the sum of the series. You need print length of the series and the series.
Input
First line will contain a number indicating the number of test cases.
Each of the following t lines will have 3 number '3term', '3Lastterm' and 'sum'
3term - is the 3rd term in of the series,
3Lastterm - is the 3rd to last term of the series,
sum - is the sum of the series.
Output
For each input of the test case, you need to print 2 lines.
fist line should have 1 value - the number of terms in the series.
2nd line of the output should print the series numbers separated by single space.
Example
Input:
1
4 64 511
Output:
9
1 2 4 8 16 32 64 128 256
NOTE
All the values will be in the range [0, 2
64
] inclusive.
The series will have at least 6 elements.
Number of test cases ≤ 100.
The ratio in all cases will be an integer. (Thanks Mitch for pointing this out.)
All the numbers will fit in 64 bits (long long in C.) | 32,801 |
Arnook Defensive Line (KL11B)
Based on the latest intelligence reports, Chief Arnook of the northern tribe has become suspicious of the warrior nations that dwell south of the border. The chief has ordered his warriors to protect the southern border which runs parallel to the 54° latitude line and stretches between the longitudes of 1° to 1000,000,000°, inclusive.
Each warrior is assigned the task of protecting a segment of the border defined to lie between longitudes "a" and "b", inclusive. No two warriors are assigned to protect the exact same segment. Bound by loyalty to his chief, a warrior will inform the chief upon his arrival at his appointed post and will never leave once he arrives.
Your task is to write a program that performs the following two operations to help Chief Arnook track the status of his border protection.
+ a b
a warrior assumes his position and protects the segment between longitudes "a" and "b", inclusive.
? c d
computes the number of warriors who completely protect the segment between longitudes "c" and "d", inclusive. The segment between the longitudes "c" and "d", inclusive, is said to be completely protected by a warrior X if and only if warrior X protects a segment between "a" and "b", inclusive, and a ≤ c ≤ d ≤ b.
Input
The input starts with an integer N (1 ≤ N ≤ 500000), on a line by itself, that indicates the number of operations. Each of the following N lines contains one operation. The description of an operation consists of a character "+" or "?" followed by two integers on a line by itself. The entries on a line are separated by single blank spaces.
Output
There is one output line for each input line that starts with the operation "?". The output consists of a single integer that represents the number of warriors who completely protect the corresponding segment at the time.
There is no output for input lines that start with the character "+".
Example
Input:
9
+ 5 10
+ 7 20
+ 3 15
? 9 12
+ 10 20
? 8 9
+ 6 30
? 8 9
? 9 12
Output:
2
3
4
3 | 32,802 |
Team Nim (TEAMNIM)
Elayne and Nynaeve have teamed up against Aviendha and Birgitte to play a game of Nim. There are 3 piles of coins with X, Y and Z coins initially. In each turn the current player selects any non-empty pile, and removes any non-zero number of coins from that heap. Then play passes to the next player. The team whose player cannot make any valid move, loses, and the other team wins the game. Assume that all the players play optimally. Find out which team wins the game.
Input
The first line contains T, the number of test cases. T test cases follow. The first line of each test case contains 3 integers X, Y, Z. This is followed by 4 lines containing the names "Elayne", "Nynaeve", "Aviendha", "Birgitte" (without quotes) in some order. This denotes the order of play. The player listed first gets the first turn, the next listed player gets the next turn and so on. After the player listed fourth, turn comes back to the player listed first and play continues.
Output
Output T lines, each containing the winner's description for the corresponding test case. Output "Elayne/Nynaeve" (without quotes) if Elayne and Nynaeve's team wins. Output "Aviendha/Birgitte" (without quotes) if Aviendha and Birgitte's team wins.
Constraints
T ≤ 50000
1 ≤ X, Y, Z ≤ 1000000000
Example
Input:
3
1 1 1
Elayne
Nynaeve
Aviendha
Birgitte
2 2 1
Aviendha
Elayne
Birgitte
Nynaeve
3 1 3
Elayne
Nynaeve
Birgitte
Aviendha
Output:
Elayne/Nynaeve
Aviendha/Birgitte
Elayne/Nynaeve
Explanation
In the first test case, the players do not really have any choice. Elayne, Nynaeve and Aviendha empty one pile each on their turn, and Birgitte cannot make any valid move after that.
In the second test case, Aviendha should empty the third pile of 1 coin. Now if Elayne takes 2 coins from a pile, Birgitte takes 2 coins from the other pile, leaving Nynaeve with no move. Or if Elayne takes 1 coin from a pile, Birgitte takes 1 coin from the other pile, and play will continue to leave Elayne with no move on her next turn.
In the third test case, Elayne and Nynaeve should each take 3 coins and empty a pile. Birgitte is forced to take the last coin leaving Aviendha with no move. | 32,803 |
Lights and Switches (LIGHTPZ)
On his birthday, Perrin received a very unusual puzzle. It consists of an N×N grid of lightbulbs, all of them initially at the off state. The goal is to turn on some of the lights, such that there is exactly one lit bulb in each row, and exactly one lit bulb in each column. Normally this would be an easy exercise, but this puzzle has an additional constraint. For each lightbulb, there is exactly one critical moment of time that the lightbulb can be switched on. As Perrin is a busy man, he does not want to spend a lot of time on the puzzle. Help Perrin calculate the minimum time taken to achieve the goal. Note that the time taken to solve the puzzle is defined as the time difference between the first and the last switching on events.
Input
The first line contains T, the number of test cases. T test cases follow.
The first line of each test case contains a single integer N. N lines follow each containing N integers. The j th integer in the i th of these lines represent the critical time for the bulb in row i, column j.
For any two lightbulbs, the critical times will be different
Output
Output T lines, each with one integer as the answer for the corresponding test case.
Constraints
T ≤ 100
1 ≤ N ≤ 50
0 ≤ critical times ≤ 1000000000
Example
Input:
2
2
3 6
9 8
4
10 41 38 66
91 13 95 70
49 32 43 52
51 98 36 19
Output:
3
29
Explanation
In the first test case, one can either turn on bulbs at times 3 and 8, or at times 6 and 9.Time taken to solve is 5 for the first option and 3 for the second. So the answer is 3.
In the second test case, one optimal way is to turn on lights at times 41, 43, 51, 70. | 32,804 |
Adventure (ADVNTURE)
Rand has been sitting in a spaceship at the point (0, 0, 0) for a long time. One day, he got bored and decided to undertake an adventure.
Deciding upon an adventure has several complicated steps. First, Rand chooses a destination point (x, y, z) different from (0, 0, 0) such that 0 <= x <= A, 0 <= y <= B, 0 <= z <= C. To go to this point, Rand travels in a straight line from the origin. As a result, he might encounter several other lattice points in the way. Each part of the journey between two consecutive lattice points encountered is called a phase.( For example if (x, y, z) = (1, 2, 3) then there is only one phase (0, 0, 0) → (1, 2, 3), while if (x, y, z) = (3, 0, 3) then there are 3 phases (0, 0, 0) → (1, 0, 1) → (2, 0, 2) → (3, 0, 3) ).
In each phase Rand chooses one of K different activities that he can undertake to pass the time. You need to calculate the total number of different adventures possible, modulo 1000000007 (1e9+7). Two adventures are considered different if they have different destination points, or if the activity undertaken during any of the corresponding phases is different.
Input
The first line contains the number T, the number of test cases.
T lines follow, each contains the integers A, B, C, K, corresponding to one test case
Output
Output T lines, each with one integer as the answer for the corresponding test case.
Constraints
T <= 1000
0 <= A, B, C <= 50000
1 <= K <= 10
Example
Input:
3
0 0 5 2
0 2 2 5
4 4 4 9
Output:
62
100
53388
Explanation
In the first test case, if Rand chooses (0, 0, 1) as destination point, then there are 2 possible adventures. Similarly for (0, 0, 2), (0, 0, 3), (0, 0, 4) and (0, 0, 5), the number of adventures corresponding to each are 4, 8, 16, 32 respectively. The total number of adventures is 2+4+8+16+32=62.
In the second test case, for points (0, 0, 2), (0, 2, 0) and (0, 2, 2) there are 25 adventures each, while for the rest of the 5 valid points, there are 5 adventures each. So total is 100. | 32,805 |
Fun with numbers (NUMPLAY)
Consider a set of 4 numbers {1, 3, 5, 7}. Form a number using these digits in the set under the following constraints,1 can be followed only by 3 (i.e. the number may contain 13 but not 15 or 17 or 11 eg:13573 is valid but not 113573), 3 can be followed only by 1 and 5, 5 can be followed only by 7, 7 can be followed only by 5 and 3.
Find the number of such numbers of length n.
e.g.: 37, 51, 53, 71 are all not a valid number of length 2. 131 is a valid number of length 3. 1357 and 1313 are all a valid number of length 4 but 11 or 1537 or 15 or 17 or 33 are not valid numbers.
Input
t, First line of input contains number of test cases 0 <= t <= 40.
Remaining t lines consist of length n for each test case 0 <= n <= 10000.
Output
Output the number of possible numbers of length n followed by a line (note long long int in C++ may not be sufficient.)
Example
Input:
3
2
1
4
Output:
6
4
13
Note: time limit is reduced for checking the accuracy. | 32,806 |
G-One Sort (GONESORT)
After Killing RaOne G-One had nothing to do, so he started reading books and became an avid book reader.
To avoid purchasing books he started working in a library.
Every evening he had to arrange the books on the shelf in increasing order of their serial number.
Every book in the library is numbered.
..
G-One found an ingenious way of arranging the books. He can remove any book from the shelf and put it either at the beginning or at the end of the shelf.
For example if the books are arranged in the order below:
2 3 1 7 4 5 6
he can make it sorted by removing '1' and placing it at the beginning and then removing '7' and placing it in the end.
Since the book shelf can be very big and can have a large number of books, he needs your help to tell him the minimum remove and place operations he needs to do.
Can you help him?
Input
1st line of the input contains number 't' denoting the number of shelves in the library. 2*t lines follow this
1st line of each test case will have single number 'b' - denoting number of books on the shelf.
2nd line will contain b numbers, each bi denoting the serial number of the book.
Output
For each test case output a single integer denoting the minimum number of remove and place operations needed to arrange the shelf.
Example
Input:
3
7
2 3 1 7 4 5 6
5
1 2 3 4 5
6
6 5 4 3 2 1
Output:
2
0
5
NOTE
All the values will be in the range [0, 10
7
], number of test cases ≤ 100. | 32,807 |
Arithmetic Evaluation (ARTHEVAL)
Evaluate a parenthesized expression of single-digit positive integers and the binary operators +, -, *.
The order of operations differs from the canonical one in that operations have no precedence; they are simply evaluated from left-to-right, with only parentheses affecting the order of evaluation.
Every intermediate step is guaranteed to have absolute value no greater than 1,000,000,000.
Input:
Input is an arithmetic expression of single-digit positive integers, the binary operators +, -, * and parentheses ( ). The arithmetic expression will be well-formed and will have no spaces.
Output:
The evaluated value of the arithmetic expression.
Example Input 1:
Example Input 2:
Example Input 3:
1*2+1
1+1*2
(5*6)-(4+(1))
Example Output 1:
Example Output 2:
Example Output 3:
3
4
25 | 32,808 |
Lucifer Sort (LUCISORT)
Lucifer is as bored as G-One after the defeat of Raone. he has no computer game to play. He Like g-One started reading books and Unlike G-One he bought a big book shelf and lots of books. He labelled all books with serial numbers. (All books have different serial numbers).
He invites his friends and small kids to home and allows them to read books. But the problem is everyone replaces the books anywhere on the shelf.
At the end of the day Lucifer has to sort all the books in increasing order of serial number on the shelf from left to right. The problem is he knows just one way of sorting called LUCIFER SORT.
He can pick a book from anywhere on the shelf but can replace it only in the center of the remaining books.
For example of the books are in order: 2 1 3 4 5 6
The steps of sorting are
1 3 4 2 5 6 - Pick 2 and place between between 4 and 5 in (1 3 4 5 6)
1 4 2 3 5 6 - Pick 3 and place between between 2 and 5 in (1 4 2 5 6)
1 2 3 4 5 6 - Pick 4 and place between between 3 and 5 in (1 2 3 5 6)
Assuming positions are numbered from 1 to N.
While replacing, if number of books left is even then it is put back between n/2 and n/2+1 position. If the number of books left is odd, it is put back between (n+1)/2 and (n+1)/2+1 position.
Since the number of books are large, he needs your help to tell me number of steps he needs to sort the shelf.
Input
First line contains number of shelves.
For each shelf there are 2 lines:
First line will have number of books.
Second line will have the serial number of the books at the end of the day.
Output
Single line telling how many books he needs to remove and replace.
If there is no way he can sort the books by this process Print "YOU ARE DOOMED" without the quotes.
Example
Input:
3
6
1 2 3 4 5 6
6
2 1 3 4 5 6
6
6 5 4 3 2 1
Output:
0
3
6
All the values will be in the range [0, 10
7
]
number of test cases ≤ 100. | 32,809 |
lcm addition (ADDLCM)
Mao is very good in mathematics, he likes to play with numbers and number theory is his favorite chapter. Once he decided to give a question to Kalyu his friend. Now Kalyu is always busy in writing articles, as he likes maths but articles is his passion and source of income too, so he can’t give much time solving that maths question, but he too don’t want to hurt his friend, so help Kalu in his problem?
Given a, b such that a ≤ b calculate the addition:
LCM(a, b) + LCM(a + 1, b) + ... + LCM(b, b), where LCM(a, b) denotes the Least Common Multiple of the integers a and b.
Since, output may be very large, take the mod 10
9
+7
Input
First line consists of T = number of test cases, next T line will contain a and b.
Output
For each T lines, print the required output.
Constraints
T ≤ 100000
1 ≤ a ≤ b ≤ 1000000
Example
Input:
3
1 6
10 15
41 90
Output:
66
675
139860 | 32,810 |
Amusing numbers (TSHOW1)
Amusing numbers are numbers consisting only of digits 5 and 6. Given an integer
k
, display the
k
-th amusing number.
Input
FIrst line consists of integer
N
representing number of test cases
Next
N
lines consist of
N
integers (1 <=
k
<= 10^15)
Output
N
lines each displaying corresponding
k
-th amusing number
Example
Input:
2
1
5
Output:
5
65 | 32,811 |
SQUARE TO SQUARE (SQ2SQ)
There are squares whose digits can be rearranged to make another squares. Lets call them S2S numbers.
for example: 144 → 441
Input
Single line containing two integers X Y (Xth, Yth term in the list of S2S numbers). Xth, Yth term ≤ 10
12
.
Output
Print all the numbers from Xth to Yth term of S2S numbers list (both inclusive).
Example
Input:
1 3
Output:
144
169
196
(
Source Code Limit= 500B
)
Note: 1 → 100 → 1 or other similar numbers are NOT S2S numbers (example 9 → 900 → 9)
Try Tutorial at
SQ2SQ2
. | 32,812 |
Answer the boss! (RPLA)
Eloy is a hard worker man, however, he is constantly bullied by his superiors, molested by this, one day he was wondering in what “rank” you are, so you can bully the people with lower ranks, also to discover who can really bully Eloy!.
Now, given the number of employees and the number of relations between them, Eloy need you to output the “rank” which employee is in, being 1 the “boss” (not bullied by anybody) and the employee who are in these ranks
Input
There will be an integer T denoting the number of test cases, then, T test cases will follow. Each test case starts with two integers N and R, the number of employees and the number of relations between them. The next R lines consists of two integers R1 and R2, meaning that “employee R1 is lower than employee R2's rank”.
Output
You will output for each test case the string “Scenario #i:” where i is the test case you are analyzing, after that, you will print N lines, for each line you will output the rank of the employee and the employee itself, if there is the same rank for several employees, then output them lexicographically ordered (the first is the lower.)
Sample
Input:
2
5 6
2 0
2 4
1 4
1 2
3 2
4 0
5 4
1 0
2 0
3 2
4 2
Output:
Scenario #1:
1 0
2 4
3 2
4 1
4 3
Scenario #2:
1 0
2 1
2 2
3 3
3 4
Blank line between test cases for clarification and separation. Please note that can be more than one "boss" (not bullied by anybody.)
Constraints
1 ≤ N ≤ 1000; 1 ≤ R ≤ 10000 | 32,813 |
Blueberries (RPLB)
Teresa picked up enough strawberries, now she wants to pick blueberries from the magical blueberry bush from Rainbowland.
Knowing her previous experience with the strawberries, Teresa wants to pick up the blueberries in a way that she may not exceed the limit proposed.
When picking the blueberries, she noticed that if she pick from the bush i, she couldn't pick the blueberries at the bush i+1 (some sort of magic in rainbowland).
Worried about this, Teresa wants to know the maximum blueberries she can pick, given the number of bushes and the number of blueberries in each bush.
Input
Will contain an integer T, then, T cases will follow, each case starts with a number N and K, being N the number of bushes and K the number of blueberries Teresa will pick as maximum, the next line contains N integers, each one representing the blueberries there is on the i-th bush.
Output
You will output for each test case the string:
“Scenario #i: “
where i is the test case you are analyzing, then, an integer denoting the maximum number of blueberries you can grab.
Example
Input:
2
5 100
50 10 20 30 40
5 87
21 45 30 12 14
Output:
Scenario #1: 90
Scenario #2: 65
Output explanation (first scenario)
Teresa picks the 1
st
blueberry bush (50), she cannot pick the 2
nd
, she decides not to pick until the 5
th
one where she picks the “40” blueberry, she could pick the 3
rd
bush, but she would exceed the limit (100).
Output explanation (second scenario)
Teresa picks the 1
st
, the 3
rd
and the 5
th
bush, total of (21+30+14 = 65) blueberries
CONSTRAINTS
1 <= N <= 1000
1 <= K <= 1000 | 32,814 |
Coke madness (RPLC)
David likes coke, lets say he likes it a lot... One day he was walking by a narrow street when he sees a lot of bottles of cokes, from different brands, he wants to drink it all, but he noticed that one brand gives him power, the other brand weaken him, now, he can wait and regain more energy, but he don't want to do that, he will wait at the beginning and, when he has the sufficient energy he will drink all the cokes in the street.
Please, help him find when he will be in the perfect moment to drink all the cokes.
Input
Will start with an integer T denoting the number of test cases, then, T lines will follow, for each test case, there will be an integer N, then, in the next line will be N integers, this will be the number of cokes, and the values of the cokes in the floor (the positive one gives energy, the negative ones will take his energy).
Output
Each test case will output the string "
Scenario #i:
" where i is the number of test case analyzed, followed by the minimum energy required by David to pass the street.
Example
Input:
2
5
4 -10 4 4 4
5
1 2 3 4 5
Output:
Scenario #1: 7
Scenario #2: 1
“The life of David should never reach 0 or less”
Constraints
1 ≤ N ≤ 1000000
-10000000 ≤ Ni ≤ 10000000 | 32,815 |
Database (RPLD)
Gaby enjoy working in a database of a very important university, this university has students of course, each student can see as many subjects they want, however, the database suffered an attack by a group of hackers, now, Gaby needs to see the backup files, but then she noticed that some of the backup files are corrupted as well... For example, the backup file can show that a student is seeing 2 same subjects, desperate, she needs help on this task.
It is known that several students (different ones) can see the same subject, however, one single student cannot see the same subject (this would seem ridiculous), if one student sees the same subject two or more times, this test would belong to a corrupted file.
Input
First line will contain an integer T, representing the cases to evaluate, the next T cases will start with a N and R, both integers, denoting the number of students and the number of lines the database have, the next R lines contains two integers I and C, I stands for the ID of the students and C for the subject code.
Output
You will output T lines for each test case, starting with the string “
Scenario #i:
“ where i is the test case you're evaluating, then, you should output the string “impossible” if the database file on evaluation is corrupted and the string “possible” if its not.
Example
Input:
2
2 4
1 6102
1 6103
2 6102
2 6103
2 4
1 6102
1 6102
2 6102
2 6103
Output:
Scenario #1: possible
Scenario #2: impossible
Constraints
1 <= N <= 10000
1 <= R <= 100000
1 <= I <= N
1000 <= C <= 9999 | 32,816 |
Espionage (RPLE)
Marcos the little one decided to build and manage an espionage agency, he was happy working as the chief of his agency, hiring spies to spy everybody in the country! But he realized that some of their own spies are spying themselves, of course, this is bad to the business and he don't want this to happen, he wants a program to alert him whenever a spy is spying another spy.
Input
Will consists in T test cases, then, T cases will follow, starting from two integers N and R, each one denoting the number of persons to evaluate and the number of relationships spy-person each one has, then, R lines will follow and will contain two integers R1 and R2, meaning that R1 spies R2.
Output
Will consist in T lines, starting from the string “
Scenario #i:
“ where i is the number of the test case you're analyzing, print the string “
spying
” if each spy has as a target a civilian, print “
spied
” otherwise.
Input
3
3 2
0 1
2 1
3 3
0 1
2 1
0 2
4 2
2 3
0 1
Output
Scenario #1: spying
Scenario #2: spied
Scenario #3: spying
Constraints
1 <= N <= 1000
1 <= R <= 10000
Explanation of the second test case:
Spy 0 spies civilian 1, spy 2 spies civilian 1, spy 0 spies spy 2. (Spied case). | 32,817 |
Fast Sum of two to an exponent (FAST2)
There is people that really like to do silly thinks, one of them is sum the numbers from 2
0
to 2
n
, task is actually really simple, just do a ultra fast sum of term 2
0
to 2
n
.
Input
The first line starts with a number, T, which is the number of test cases, T lines will follow.
Each line contains the number "n".
0 ≤ n ≤ 500
Output
Output the sum from 2
0
to 2
n
MODULO 1298074214633706835075030044377087.
Example
Input:
3
0
1
2
Output:
1
3
7
Extra: TLE is equal to 0.15s | 32,818 |
Zoom Operation (ZOOMOP2)
Zoom Operation
Use only 4 symbols: + ? - # (in circular order beginning with +) to zoom the number given.
Every segment of the number has one symbol more than the previous. (First Segment has a single symbol).
First symbol of every segment starts in the same column/row where the previous segment's last symbol ends.
First segment (orange color) → 1 symbol + (first symbol only.)
Second segment (green color) → 2 symbols ? - (starts with second symbol as first segment uses single element.)
Third segment (yellow color) → 3 symbols # + ? (starts with fourth symbol as 3 symbols have been used by first and second segments.)
Colors are shown for better understanding. See picture for more clarification.
Input
Given a number you have to apply zoom operation and print it.
Output
Print the pattern after Zoom Operation.
Examples
Input:
1
Output:
+
Input:
2
Output:
+?
-
-?+#
#
+
?
-#+?-
Input:
3
Output:
+?
-
-?+#
#
+
?
-#+?-#
+
?
-
#
+
#-?+#-?
Input:
4
Output:
+
?-#
+
?
Input:
5
Output:
?+
-
#+?-
#
+
?
-?+#-
For any clarification, refer to the picture above.
Try tutorial at
ZOOMOP
. | 32,819 |
Recycled Numbers (GCJ2012C)
Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers.
Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros.
Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B?
Limits
1 ≤ T ≤ 55
A and B have the same number of digits.
1 ≤ A ≤ B ≤ 2000000.
Are we sure about the output to Case #4?
Yes, we're sure about the output to Case #4.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ≤ n < m ≤ B.
Example
Input:
4
1 9
10 40
100 500
1111 2222
Output:
Case #1: 0
Case #2: 3
Case #3: 156
Case #4: 287 | 32,820 |
EASY MATH (EASYMATH)
You will be given 4 numbers: n m a d.
Find count of numbers between n and m (inclusive) not divisible by (a) or (a+d) or (a+2d) or (a+3d) or (a+4d).
Input
First line has number t - number of test cases.
Each test case has 4 numbers n m a d.
Output
Single line having single number giving the count.
Constraints
1 ≤ n ≤ m ≤ 2
32
1 ≤ a ≤ 2
32
1 ≤ d ≤ 2
32
2 ≤ t ≤ 100
Example
Input:
3
1 10 2 2
20 100 3 3
100 1000 4 5
Output:
5
54
543
Also try the challenge version at
EASYMATC | 32,821 |
Bazinga! (DCEPC505)
Sheldon is very proud of his intelligence. To test his intelligence Howard designs a puzzle and asks him to solve it. The puzzle consists of special numbers which can be obtained by multiplying exactly two distinct prime numbers. Sheldon has to tell Howard what is the Kth element of this series. Help him.
For Example 6, 10, 14, 15 are the first few members of this series whereas 4, 9 and 12 are not.
Input
First line specifies T, the number of test cases.
Next T lines each gives 1 number, K
Output
Output 1 line for each test case giving the Kth element of this series.
Constraints
1 <= T <= 1000
1 <= K <= 2000000
Example
Input:
4
2
3
5
7
Output:
10
14
21
26 | 32,822 |
The Indian Connection (DCEPC504)
Rajesh Kuthrapali has a weird family structure. Every male member gives birth to a male child first and then a female child whereas every female member gives birth to a female child first and then to a male child. Rajesh analyses this pattern and wants to know what will be the Kth child in his Nth generation. Help him.
Note:
Every member has exactly 2 children.
The generation starts with a male member (Rajesh).
In the figure given below:
M ------------ 1st generation
/ \
/ \
/ \
M F ------- 2nd generation
/ \ / \
M F F M
|
3rd child of 3rd generation
Input
First line specifies T, the number of test cases.
Next T lines each gives 2 numbers, N and K.
Output
Output 1 line for each test case giving the gender of the Kth child in in Nth generation.
Print “
Male
” for male “
Female
” for female (quotes only for clarification).
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ 10000
1 ≤ K ≤ min(10
15
, 2
(n-1)
)
Example
Input:
4
1 1
2 1
2 2
4 5
Output:
Male
Male
Female
Female | 32,823 |
Save Thy Toys (DCEPC501)
Leonard is very fond of buying rare and expensive science fiction toys. He keeps his collection in a sequential order of the date on which the toy was bought in a special closet so that his roomie Sheldon never gets hold of his toys. But because of his bad luck Leonard once loses a bet to Sheldon and Sheldon demands a share Leonard’s toys. Since Leonard doesn’t want to loose much money, he decides upon a strategy to reduce his loss to minimum.
Leonard, beginning from the first toy in his closet will pick some toys, say "x" toys in sequence. Sheldon will then pick the next "x" toys (Note that Sheldon picks equal no. of toys as picked by Leonard in his move unless the remaining toys are less than "x". In that case he picks all of the remaining). This will keep going on till no more toys are left in the closet for Leonard to pick. You are given the sequence of toys with their price. Help Leonard in maximizing the total price of all toys he picks.
Leonard in his each turn can either pick only 1 or 2 or 3 toys ("x" described above can take value either 1, 2 or 3).
Input
First line specifies T, the number of test cases.
Each test case contains N in the first line. Second line contains N integers as described above.
Output
Output 1 line for each test case giving the maximum possible value of the total sum of all toys Leonard picks.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 100000
1 ≤ Price of toys ≤ 1000000
Example
Input:
2
4
5 4 3 2
6
10 8 7 11 15 20
Output:
12
53
Explanation:
In the 1st case, Leonard picks 3 toys in his first move with value 5, 4, 3 and Sheldon has no choice but to pick the last.
In the 2nd case, Leonard picks 10, 8. Then Sheldon picks 7, 11. Then Leonard picks the rest. | 32,824 |
Just Like the Good Old Days (DCEPC502)
Sheldon and Penny are neighbours. Penny really likes grid games so Sheldon develops a new grid based game for Penny. The game consists of a M×N grid (M rows, N columns) and an infinite number of black and white knights. The grid has some open and some closed blocks. In the beginning of the game each player chooses his colour of knight. The rule says that each player on his turn can place his knight on any of the open blocks such that none of his knights attack any knight of other colour (he may attack any knight of the same colour). You are given a M×N grid. Specify the maximum number of knights (black and white) which can be placed on the grid. The game stops when any one player cannot place any more knights.
Note: In one turn, Knight can move exactly two squares horizontally and one square vertically, or two squares vertically and one square horizontally.
Input
First line specifies T, the number of test cases.
First line of each test case gives M and N separated by a single space
This is followed by a grid of size M×N consisting of ‘.’ And ‘#’. Each ‘.’ represents an open position and each ‘#’ represents closed position.
Output
Output 1 line for each test case giving the maximum possible value of knights that can be placed.
Constraints
1 <= T <= 5
1 <= M, N <= 10
0 <= Number of open positions "." <= 10
Example
Input:
2
3 3
...
...
...
3 3
...
.#.
...
Output:
7
6 | 32,825 |
Tied Down (TDOWN)
As we all know, Bessie the cow likes nothing more than causing mischief on the farm. To keep her from causing too much trouble, Farmer John decides to tie Bessie down to a fence with a long rope. When viewed from above, the fence consists of N posts (1 <= N <= 10) that are arranged along vertical line, with Bessie's position (bx, by) located to the right of this vertical line. The rope FJ uses to tie down Bessie is described by a sequence of M line segments (3 <= M <= 10,000), where the first segment starts at Bessie's position and the last ends at Bessie's position. No fence post lies on any of these line segments. However, line segments may cross, and multiple line segments may overlap at their endpoints.
Here is an example of the scene, viewed from above:
To help Bessie escape, the rest of the cows have stolen a saw from the barn. Please determine the minimum number of fence posts they must cut through and remove in order for Bessie to be able to pull free (meaning she can run away to the right without the rope catching on any of the fence posts). All (x,y) coordinates in the input (fence posts, Bessie, and line segment endpoints) lie in the range 0..10,000. All fence posts have the same x coordinate, and bx is larger than this value.
Input
Line 1: Four space-separated integers: N, M, bx, by.
Lines 2..1+N: Line i+1 contains the space-separated x and y coordinates of fence post i.
Lines 2+N..2+N+M: Each of these M+1 lines contains, in sequence, the space-separated x and y coordinates of a point along the rope. The first and last points are always the same as Bessie's location (bx, by).
Output
Line 1: The minimum number of posts that need to be removed in order for Bessie to escape by running to the right.
Example
Input:
2 10 6 1
2 3
2 1
6 1
2 4
1 1
2 0
3 1
1 3
5 4
3 0
0 1
3 2
6 1
Output:
1
Output explanation:
Removing either post 1 or post 2 will allow Bessie to escape. | 32,826 |
Fibonacci With a Twist (FIBTWIST)
Fibonacci numbers are given by
f(n) = f(n-1) + f(n-2)
with f(0) = 0 and f(1) = 1.
first number of series ------ 0 1 1 2 3 5 8 13
Now let's have a new series called "Fibonacci Twist" which is given by
ft(n) = ft(n-1) + ft(n-2) + (n-1)
with ft(0) = 0 and ft(1) = 1.
with first few number in the series ----- 0 1 2 5 10 19 34 59
Now your task is to find ft(n).
Since the number can be big you have to find the result mod M.
Input
first line having single number 't' -- number of test cases.
Next t lines have 2 number each 'n' and 'M'
Output
Single number given the n-th term mod M
Example
Input:
3
5 20
10 77
15 111
Output:
19
45
69
Constraints
10 <= t <= 100
0 <= n <= 10^9
100 <= M <= 10^9
Explanation
ft(5) is 19. 19 % 20 = 19
ft(10) is 276. 276 % 77 = 45
ft(15) is 3177. 3177 % 111 = 69 | 32,827 |
Combat on a tree (COT3)
Alice and Bob are playing a game on a tree of n nodes. Each node is either black or white initially.
They take turns to do the following operation:
Choose a white node v from the current tree;
Color all white nodes on Path(1, v) to black.
The player who takes the last turn wins.
Now Alice takes the first turn. Help her find out if she can win when they both use optimal strategy.
Input
The first line of input contains a integer n representing the number of nodes in the tree. 1 ≤ n ≤ 100000
The second line contains n integers c1, c2 ... cn. 0 ≤ ci ≤ 1.
ci = 0 means the ith node is white initially and ci = 1 means black.
Next n-1 lines describes n-1 edges in the tree. Each line contains two integers u and v, means there is a edge connecting u and v.
Output
If Alice can't win print -1.
Otherwise determine all the nodes she can choose in the first turn in order to win. Print them in ascending order.
Example
Input #1:
8
1 1 0 1 0 0 1 0
1 2
1 3
2 6
3 4
3 5
5 7
7 8
Output #1:
5
Input #2:
20
1 1 1 0 1 1 1 0 1 0 0 0 1 0 1 0 0 0 0 0
1 2
2 3
2 4
1 5
1 6
5 7
5 8
2 9
8 10
1 11
1 12
9 13
6 14
14 15
7 16
11 17
2 18
7 19
12 20
Output #2
8
11
12 | 32,828 |
Unlock it ! Part 2 (DCEPC604)
Now you all helped Vaibhav solve the puzzle and open the gate last time (although not too much help). But as soon as he opens the gate, there is another puzzle to open the front door. Let’s see whether this time you all are able to help him or not.
Fac(n) = number of trailing zeroes in n!
Fact(n) = Fac(n) % 25 + 1
F(0) = 1
F(1) = 1
F(2) = 1
F(n) = product of all odd primes less than or equal to n (for n ≤ 10)
F(n) = 4
fact(n)
× f(n/5) × f(n/10) (for n > 10)
For every fraction, a floor value is taken for evaluation.
For eg. F(11) = 4
fact(11)
× F(floor(11/5)) × F(floor(11/10)) = 4
3
× F(2) × F(1) = 64
Given N, find the maximum value of
(a
b
) % mod
such that a and b satisfies the relation gcd(a, b) = F(N). (Gcd : Greatest common divisor.)
Input
First line gives T, total number of test cases. Next T lines give the number N.
Output
For each test case, print the desired value on a new line.
Constraints
T ≤ 10
N ≤ 10
6
mod = 10
9
NOTE: a must be ≤ 5 × F(n) and b must be ≤ 5 × F(n), a can be equal to b.
Example
Input:
1
2
Output:
1024 | 32,829 |
Davids Greed (DAVIDG)
The King David is a particularly miserly character. He has all the gold in his kingdom, and never lends a single coin to anyone. Years passed, and the streets in his kingdom, made by his father, King Enrique, started to deteriorate. The villagers couldn’t traffic with their carts without dropping some of their content.
This problem was affecting the merchants, because they were losing food and other stuff that they sell. So they decided to go to the castle and block the entrance, so the king couldn’t get out until he promised that he would restore the streets.
The King, tired by the annoyance of the people, decided to promise to restore the streets of his kingdom, but because he’s too greedy, he will restore only the ones that are important for the city, let’s call them “vital streets”.
The vital streets connect a commercial point A to a commercial point B in the city such that there will never exist 2 ways to go from point A to point B. This is given by some coordinates X and Y, you can assume the commercial point will be a single point in a space.
The original streets, built by King Enrique, connects every point with the other points, so point A is connected with point B, C, D, and so on. So restore every street would be too expensive, that’s why King David will restore only the “vital streets”, but he is not really good at this type of calculations, so he need you to write a program that help him out.
The cost of restoring a street is given by its length and some value P, that tell how much cost to restore a single unit of distance. By example, if P = 3, and the distance between points A and B is 3.5, then the total cost of restoring that street would be 3.5 * 3. Note: you have to round up the total cost of the street.
Input
The first line of input will consist of an integer T, denoting the number of test cases. Every test case will have by first line 2 integers, N and P, denoting the number of points and the unitary cost. Then N lines follow, every of them having 2 numbers Xi and Yi, denoting the coordinates in the cartesian plane of every commercial point.
Output
For each test case output a single line containing this: “Scenario #i: j”, where i is the number of the test case, starting at one, and j is the minimum cost of restoring the streets, such as the restored streets let the villagers to go from one point to another point. Since this number can be quite large, output j mod 10^9 + 7.
Example
Input:
2
4 1
35 46
29 13
44 0
27 17
3 18
18 0
11 17
2 31
Output:
Scenario #1: 56
Scenario #2: 631
Constraints
1 ≤ N ≤ 1,000
-1,000 ≤ Xi, Yi ≤ 1,000
1 ≤ P ≤ 1,000 | 32,830 |
MAXOR (MAXOR)
You are given a sequence A[1], A[2] ... A[N]. (0 ≤ A[i] < 2
31
, 1 ≤ N ≤ 12000).
A query is defined as follows:
Query(x, y) = Max { a[i] xor a[i+1] xor ... xor a[j] ; l ≤ i ≤ j ≤ r }.
l = min ( ((x+lastans) mod N)+1, ((y+lastans) mod N)+1 ).
r = max ( ((x+lastans) mod N)+1, ((y+lastans) mod N)+1 ).
lastans[1] = 0 , lastans[i] = Query[i-1].
Given M queries, your program must output the results of these queries. (0 ≤ M ≤ 6000).
IMPORTANT : PROBLEM ENHANCED. ( I'M SO SORRY.. )
Input
The first line of the input file contains 2 numbers : N M.
In the second line, N numbers follow.
M lines follow, where line i contains 2 numbers xi and yi.
Output
Your program should output the results of the M queries, one query per line.
Example
Input:
3 3
1 4 3
0 1
0 1
4 3
Output:
5
7
7 | 32,831 |
Ninja (VUDBOL5)
A ninja is practicing and he is very fast he can make two cuts in one second and his master give he a new challenge. The master take a cube, thrown through the air and quickly says four numbers. The ninja has to think fast to make two cuts and get desired values.
Given a cube of size N*N*N, he need to cut it into four entire pieces of size A, B, C and D. He needs to divide the cube in these pieces with only two cuts, one vertical and one horizontal.
Input
The input consists in multiple test cases.
Each test case begins a line containing five integers N (2 <= N <= 1000000), A, B, C y D (1 <= A, B, C, D <= 2^63).
The end of input is indicated by a line with five zeros. This is not a part of any test case.
Output
For each test case print "Possible" if it is possible to obtain the pieces and print "Impossible" if it is not possible to obtain the pieces with two cuts.
Example
Input:
2 5 1 1 1
2 2 2 2 2
3 12 3 6 6
0 0 0 0 0
Output:
Impossible
Possible
Possible | 32,832 |
Planning Poker (VUDBOL7)
Planning Poker, also called Scrum poker, is a consensus-based technique for estimating, mostly used to estimate effort or relative size of user stories in software development.
A typical Planning Poker Deck has cards showing the Fibonacci sequence including a zero: 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. other decks use similar progressions.
We have some tasks estimated with other complexities from 1 to 10000000.
We need to estimate the complexity of all tasks using the Fibonacci sequence used in Planning Poker. The rule is that the old complexity will change to the valid complexity more close. But if two complexities are in equal distances take the higher.
Input
The input consists of multiple test cases.
Each test case begins with a line containing an integer “N” (1 ≤ N ≤ 100000) the number of tasks. In the following line are the complexities of "N" tasks from "0" to "N-1" (1 ≤ task[i] ≤ 10000000).
The end of input is indicated by a line with one zero. This is not a part of any test cases.
Output
For each test case print the list of new complexities sorted in ascending order. Print a space character between two complexities.
Example
Input:
5
1 2 3 4 5
5
7 8 9 11 10
0
Output:
1 2 3 5 5
8 8 8 8 13 | 32,833 |
Book Shelves (SHELF)
When Farmer John isn't milking cows, stacking haybales, lining up his cows, or building fences, he enjoys sitting down with a good book. Over the years, he has collected N books (1 ≤ N ≤ 100,000), and he wants to build a new set of bookshelves to hold them all.
Each book i has a width W(i) and height H(i). The books need to be added to a set of shelves in order; for example, the first shelf should contain books 1...k for some k, the second shelf should start with book k+1, and so on. Each shelf can have a total width of at most L (1 ≤ L ≤ 1,000,000,000). The height of a shelf is equal to the height of the tallest book on that shelf, and the height of the entire set of bookshelves is the sum of the heights of all the individual shelves, since they are all stacked vertically.
Please help FJ compute the minimum possible height for the entire set of bookshelves.
Input
Line 1: Two space-separated integers: N and L.
Lines 2..1+N: Line i+1 contains two space-separated integers: H(i) and W(i). (1 ≤ H(i) ≤ 1,000,000; 1 ≤ W(i) ≤ L).
Output
Line 1: The minimum possible total height for the set of bookshelves.
Sample
Input
5 10
5 7
9 2
8 5
13 2
3 8
Output
21
Explanation
There are 5 books. Each shelf can have total width at most 10.
There are 3 shelves, the first containing just book 1 (height 5, width 7), the second containing books 2, 3 and 4 (height 13, width 9), and the third containing book 5 (height 3, width 8). | 32,834 |
Balanced Cow Subsets (SUBSET)
Farmer John's owns N cows (2 ≤ N ≤ 20), where cow i produces M(i) units of milk each day (1 ≤ M(i) ≤ 100,000,000).
FJ wants to streamline the process of milking his cows every day, so he installs a brand new milking machine in his barn.
Unfortunately, the machine turns out to be far too sensitive: it only works properly if the cows on the left side of the barn have the exact same total milk output as the cows on the right side of the barn!
Let us call a subset of cows "balanced" if it can be partitioned into two groups having equal milk output.
Since only a balanced subset of cows can make the milking machine work, FJ wonders how many subsets of his N cows are balanced.
Please help him compute this quantity.
Input
Line 1: The integer N.
Lines 2..1+N: Line i+1 contains M(i).
Output
Line 1: The number of balanced subsets of cows.
Sample
Input
4
1
2
3
4
Output
3
Explanation
There are 4 cows, with milk outputs 1, 2, 3, and 4.
There are three balanced subsets: the subset {1, 2, 3}, which can be partitioned into {1, 2} and {3}, the subset {1, 3, 4}, which can be partitioned into {1, 3} and {4}, and the subset {1, 2, 3, 4} which can be partitioned into {1, 4} and {2, 3}. | 32,835 |
To the moon (TTM)
Background
To The Moon
is a
independent game
released in November 2011, it is a role-playing adventure game powered by
RPG Maker
.
The premise of
To The Moon
is based around a technology that allows us to permanently reconstruct the memory on dying man. In this problem, we'll give you a chance, to implement the logic behind the scene.
Description
You‘ve been given N integers A[1], A[2],..., A[N]. On these integers, you need to implement the following operations:
C l r d: Adding a constant d for every {Ai | l <= i <= r}, and increase the timestamp by 1, this is the only operation that will cause the timestamp increase.
Q l r: Querying the current sum of {Ai | l <= i <= r}.
H l r t: Querying a history sum of {Ai | l <= i <= r} in time t.
B t: Back to time t. And once you decide return to a past, you can never be access to a forward edition anymore.
.. N, M ≤ 10^5, |A[i]| ≤ 10^9, 1 ≤ l ≤ r ≤ N, |d| ≤ 10^4 .. the system start from time 0, and the first modification is in time 1, t ≥ 0, and won't introduce you to a future state.
Input
n m
A1 A2 ... An
... (here following the m operations.)
Output
... (for each query, simply print the result.)
Example
Input 1:
10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4
Output 1:
4
55
9
15
Input 2:
2 4
0 0
C 1 1 1
C 2 2 -1
Q 1 2
H 1 2 1
Output 2:
0
1 | 32,836 |
Amazing Maze (DCEPC701)
Chintu and his father Nikka, on their vacations, went to The Amazing Maze. But unfortunately, Chintu is has been separated from his father. His father Nikka has to find him as soon as possible in the maze or else Chintu will start crying soon.
The Amazing Maze is actually pretty amazing! The maze is built in a rectangular grid fashion. There are walls (#) and walking cells (.) in the grid. One can only walk through walking cells and so cannot jump off the wall. The amazing part is that each wall becomes a walking cell at some point of time (Neglect the transition time). Alternatively one can say that at some time t1 units, the wall will become walking cell and so one can step on to it at t1 time
and at any time after t1
. One can only move to adjacent walking cells from a walking cell. Adjacent cells mean the immediate up, down, right and left walking cells. It takes 1 unit of time to go from current cell to any adjacent cell. One can also wait on a particular walking cell for an adjacent wall to become a walking cell.
Nikka has the map of the maze with the information of the time at which the walls becomes walking cells.
Also he knows at which walking cell he is situated and at which walking cell Chintu is situated.
Help Nikka find out the minimum time required to reach to his son Chintu.
Input
First line contains T, the number of test cases.
Each case begins with two integers, M and N, the dimensions of maze.
Next contains M lines each containing N characters. Each character is either a “#” or a “.” as described above. This maze is the snapshot at time t=0.
Next M lines contain N space separated non negative integers. For each “.”, there will be a 0 and for each “#”, there will be a positive integer which represent the time at which that wall (#) will become a walkable cell.
Next line contains x1 and y1 denoting the position of Nikka in the maze.
Next line contains x2 and y2 denoting the position of Chintu in the maze.
Output
Output T lines each containing an integer, the minimum time required for Nikka to reach Chintu.
Constraints
1<=T<=10
1<=M<=200
1<=N<=200
0<=x1, x2
0<=y1, y2
For all #’s, time “t” will be > 0 and <= 10^4.
Example
Input:
2
1 5
..#..
0 0 1 0 0
0 0
0 4
3 3
.##
##.
##.
0 1 2
3 4 0
6 7 0
0 0
2 2
Output:
4
4 | 32,837 |
NOS (DCEPC702)
Find the number of strings of length “N” made up of only 3 characters – a, b, c such that “a” occurs at least “min_a” times and at most “max_a” times, “b” occurs at least “min_b” times and at most “max_b” times and “c” occurs at least “min_c” times and at most “max_c” times. Note that all permutations of same string count as 1, so “abc” is same as “bac”.
Input
First line gives T, the number of test cases.
Each test case has an integer “N” on first line.
Next line contains 2 integers, min_a and max_a.
Next line contains 2 integers, min_b and max_b.
Next line contains 2 integers, min_c and max_c.
Output
Output T lines, each containing the required answer modulo 10
9
+7.
Constraints
1 ≤ T ≤ 1000
1 ≤ N ≤ 10
9
1 ≤ min_a ≤ max_a ≤ 10
9
1 ≤ min_b ≤ max_b ≤ 10
9
1 ≤ min_c ≤ max_c ≤ 10
9
Example
Input:
1
3
1 1
1 1
1 1
Output:
1 | 32,838 |
Totient Game (DCEPC703)
Bahl and Debnath are always looking up for new exciting games on the internet. Yesterday, Bahl stumbled across a new game known as “Totient Game”. He immediately showed that to Debnath. They found it pretty exciting and decided to play it. The game is as follows:
The game is played with N piles of stones.
2 players play alternatively and at each turn a player selects a pile and divides it into two unequal sized piles “i” and “j” such that Totient(i)*Totient(j)=Totient(i*j) and i+j = number of stones in that pile.
The player who is unable to make a move loses the game.
Bahl insists on starting the game first. Can you predict the winner of the game?
Assume that both player plays optimally.
http://en.wikipedia.org/wiki/Euler%27s_totient_function
Input
First line gives T, the number of test cases.
Each test starts with a line containing “N”, the number of piles.
Next line gives N space separated integers. The i
th
integer represents the number of stones in the i
th
pile.
Output
Output T lines each containing the winner of the T games. Output “Bahl” if Bahl wins the game or “Debnath” if Debnath wins the game.
Constraints
1<=T<=10
1<=N<=10^5
1<= Number of stones in each pile <=10^7
Example
Input:
1
3
1 2 3
Output:
Bahl | 32,839 |
Weird Points (DCEPC705)
Given N distinct points in a plane, a point (x1, y1) is said to be dominating another point (x2, y2) if x1>=x2 and y1>=y2.
The Dominance of a point is the absolute difference between 2 quantities – number of points dominated by this point and number of points not dominated by this point.
(excluding itself)
A Weird point is the point whose Dominance value is greater than or equal to a threshold value ‘k’. Find the number of such Weird Points among those N given points.
Input
First line gives T, the number of test cases.
Each test case consists of 2 integers in first line, N and K, as specified above.
Next N lines give the coordinates of N points in the plane. “Xi” and “Yi” are space separated.
Output
Output T lines, each containing the required answer.
Constraints
1<=T<=10
1<=N<=10^5
1<=Xi, Yi<=10^9
0<=K<=N
Example
Input:
1
4 2
3 1
7 5
2 8
6 7
Output:
2
Problem Statement and Test Cases has been updated 2012-05-17 18:10:00
. | 32,840 |
Meeting For Party (DCEPC706)
Ankur, Anuja and Jyoti are planning to have party at some place. Their houses are located at different points in a rectangular grid of size M*N. They want to meet in minimum time and then party.
The M rows and N columns rectangular grid contains some impassable points (denoted by a #), however. So none of them wants to step over these points. They can only step over passable points (denoted by a .). They can also meet at some point outside the grid. You can assume that the points outside the grid are all passable. They cannot party on an impassable point and they have their house only on passable point. They can move either to North, South, East or West passable point from the current passable point and it takes 1 unit time to do so. Also they can wait at a passable point if they want to.
Find the minimum time of meeting.
Note: Assume that they will always meet at some point.
Input
First line gives T, the number of test cases.
Each test case has two space separated integers M and N, the dimensions of the grid.
Next M lines contain N characters per line (no spaces). Characters can be either “#” (impassable) or “.” (passable) or “1” (Ankur’s house) or “2” (Anuja’s House) or “3” (Jyoti’s house). Each test case will have exactly 1 “1”, exactly 1 “2” and exactly 1 “3”.
Output
Output T lines, each containing the required answer.
Constraints
1 ≤ T ≤ 10
1 ≤ M ≤ 200
1 ≤ N ≤ 200
Example
Input:
1
4 4
#...
.2#.
..#3
1..#
Output:
4 | 32,841 |
Count on a trie (COT4)
Maintain two sets of strings
S
and
T
. Initially, each set contains an empty string with id 1.
Your program are to perform the following four operations:
Add a char
c
to the end of an existed string
Si
in
S
, then insert the new string into
S
. Since there has been
n
strings in
S
already, the new string will hold the id
n+1
.
Add a char
c
to the beginning or to the end of an existed string
Ti
in
T
, then insert the new string into
T
.
Choose two existed strings
Ti
and
Tj
from
T
, next combine them into a new one
TiTj
, then insert the new string into
T
.
Print the time that an existed string
Ti
in
T
appears in an string
Si
in
S
. Your program should print
0
if
Ti
is an empty string.
Input
In the first line, there is an integer
Q
, which means the number of operations to perform.
In the next
Q
lines,the
i
-th line describes the
i
-th operation containing some integers. Such a line may look like this:
1 Si c
2 0 Ti c
=> add
c
to the beginning of
Ti
2 1 Ti c
=> add
c
to the end of
Ti
3 Ti Tj
4 Ti Si
Q
≤ 300000, 'a' ≤
c
≤ 'z'
The number of the first operation will not exceed 100000.
The number of the third operation will not exceed 30000.
The number of fourth operation will not exceed 100000.
Output
For each
"4 Ti Si"
operation, print its result.
Example
Input:
18
1 1 a
1 2 a
1 3 b
1 2 b
1 5 a
1 5 b
2 1 1 a
3 2 2
2 0 3 b
2 1 2 b
3 2 5
3 5 2
4 7 6
4 5 6
4 3 4
4 2 4
4 2 7
4 2 6
Output:
1
1
1
2
1
2 | 32,842 |
Goto & labels (RPLG)
Vero is working on an important company, the company noticed that Vero codes using goto labels, her boss does not want Vero to code this kind of programs, the boss tells her that he will cut her payment by the number of lines contained between the label and the goto.
Vero does not know any iterative structures, and she is too worried to code the program she is asking you for, Code a solution for Vero's problem.
The solution to this is to count the lines of code that are between the label and the goto statement, having in consideration that the goto will always
return
to an existent label, the label will consist on a single string formed by letters from the 'a' to the 'z' and from the 'A' to the 'Z', all labels will have the format
:
as the goto will always contains the format
goto
;
, however, remember that before the labels and the gotos you can have an important amount of spaces that will count as an indentation of a code.
Note: An uppercase letter label is distinct from a lowercase letter label, by example: 'abc' is not equal to 'ABC'
INPUT:
The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following line will contain an integer N, then, N lines will follow, each of the next N lines will contain a string S.
OUTPUT:
Output the string “Scenario #i: “ where i is the test case you are analyzing followed by the sum of the number of lines between the label and the goto.
SAMPLE DATA:
INPUT
OUTPUT
3
6
A:
SPACES will InDeNt the CoDe
No TaBs ArE iN the >> test << data
goto A;
B:
goto B;
7
B:
A:
cin >> n;
if(n<0) then
goto A;
else
goto B;
7
A:
TumbaBicho:
printf("goto TumbaBicho");
printf("goto TumbaBicho");
goto TumbaBicho;
AA:
goto A;
Scenario #1: 2
Scenario #2: 7
Scenario #3: 7
CONSTRAINTS:
1<=N<=10000
1<= Length of string <= 1000 | 32,843 |
Hard Launching (RPLH)
Felix, the cat, decided to play in the afternoon with some melons, he built a “melon launcher” and started pointing to targets. Soon he noticed that the melons sometimes overflies the victims or don't even get close to them.
The melon launcher can be rotated so it can shoot from an angle from 0 to 45 degrees.
Felix isn't good at maths, so he ask you to code a program that, given the target (in meters) distance and the speed (in meters / sec) you can give him the perfect angle for the melon launcher.
The gravity to be considered is of 9.806 meters / sec
2
.
Pi value to be considered is 2×acos(0.0).
Input
The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following line will contain two integer numbers Ta and Sp, denoting the distance of the target and the speed of the melon respectively.
Output
Output the string “
Scenario #i:
“ where i is the test case you are analyzing followed by a single number D, denoting the Degrees necessary to do the launch, if the launching can't be done, output D as
-1
. the number must have a precision of 2 decimal digits.
Example
Input:
3
10 10
10 9
8 9
Output:
Scenario #1: 39.35
Scenario #2: -1
Scenario #3: 37.79
Constraints
0 < Ta, Sp < 10000 | 32,844 |
Ignore the bounds (RPLI)
Luis is seeing his son playing, he ask him gently in what the game consists, the boy replies “It's like this, you have a big number, a bound and a “mod” (the remainder of a division between a number and “mod”), the goal of the game is to discover the maximum sub-number you can create following this rules:”
The sequence must not decrease lower from the first digit taken.
The sequence chosen must
not
reach the bound. By example, if the first digit is 'd' and a bound 'k', the range you can take is between [d, min(d+k, 9)]
You can start from
any
digit of a number.
For any given start point, you should look for the sub-numbers making the maximum sum applied to the mod operation.
Luis, astonished by the explanation, request his son to give him an example, the boy then continues: “Suppose a number like this: 56789, a bound of 2, and a mod 10. you start with 5, being the bound of 2, this mean you can take up to the digit 7 (this means that you can always collect as many fives, sixes and sevens following the rules explained). The sub-number formed is of “5+6+7”, following the rules, we will have all others sub-numbers: “6+7+8”, “7+8+9”, “8+9” and “9”, after applying the operation, you will find that the maximum remainder of the sub-numbers sum will be of “9”, made by the sub-number “9”.
Luis is a former programmer now and he does not have the same ability he had years ago, please, help him in his task following the game previously defined.
Input
The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following cases will contain a line with an integer L, a big number N in the range [10^(L-1),(10^L)-1], an integer K denoting the bound and the M that will be the mod of the whole operation.
Output
Output the string “Scenario #i: “ where i is the test case you are analyzing followed by the maximum sum of the sub-sequence that can be formed.
Example
INPUT
OUTPUT
4
7 1235678 2 10
7 1235678 2 3
3 679 2 20
4 3457 2 10
Scenario #1: 8
Scenario #2: 2
Scenario #3: 16
Scenario #4: 9
Constraints
1<=L<=100000
10^(L-1)<=N<(10^L)-1
1<=K<=8
1<=M<=45 | 32,845 |
Just the distance (RPLJ)
Deisy is working on a robotics project, she wants to test the robot at the top before sending it to a very important company, she made a complete map for the robot, the robot is in the beta test, so it's a little dummy, the robot can't walk in diagonals, it only can walk in four directions; north, south, east or west, Deisy thinks someway this is a very bad thing, so, she wants to know if a diagonal is always the
best
path for the robot to go through.
You are going to test the robot's diagonal steps versus the real steps the robot can make from a
map A to a map B
, having in consideration that the robot can start whenever in map A or B and arrives to the nearest point in B or A, also, Deisy can choose any point as a start for the robot (this point will belong to a map) and you must
not
compare the set of points where the robot belongs.
Definition of a "map": a map is a set of stars (*) in adjacency, we define the adjacency as the four positions (north, south, east, west), meaning that a star is adjacent to other if they are communicated by one of these positions.
Input
The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following cases will contain a line with an integer N, then N lines with N characters each will follow, denoting the map the robot will have to traverse from a set of points A to a set of points B, a free space will be denoted by '-' and a occupied space by some point will be denoted by a character '*', it is guaranteed that there will be always two maps.
Output
Output the string “Scenario #i: “ where i is the test case you are analyzing followed by the option to choose, output 1 if the robot can go by its normal direction, 0 if going in diagonals is better.
Sample
INPUT
2
5
---**
---**
-----
**---
**---
4
*--*
*--*
*--*
*--*
OUTPUT
Scenario #1: 0
Scenario #2: 1
Explanation of the first case: For each point in the matrix either you start in map A or B, traversing in diagonals will always be better, the output should be zero (0).
Note: if Deisy find herself with equal distance between the diagonal and the "normal" steps of the robot, she will choose the "normal" steps as the best, in this case, the output should be 1 (normal is better).
Constraints
2<=N<=1000 | 32,846 |
IPL - CRICKET TOURNAMENT (IPL1)
NOTE: This problem needs knowledge about the game
cricket
.
Those who know the basics about IPL can skip the first paragraph.
IPL is one of the famous cricket tournaments. Every match is played between two teams. Each team has eleven players. When the first team bats, the second team bowls. The second team’s aim is to get more score/runs than the first team and the first team’s aim is to defend their score. Each team can bat either until the end of 20 overs or until they lose 10 wickets. 6 balls are bowled every over.
The possible things that can happen in any ball are dot-ball, 1 run, 2 runs, 3 runs, 4 runs, 5 runs, 6 runs, wide, no-ball, wicket. For any no-ball or a wide, 1 run is granted and the ball is not counted. Assume that these things can happen with equal probability.
You are given the overs gone, the current score/wickets and the target. Find the winning probability of the chasing team.
Input
The first line consists of an integer t, denoting the number of test cases. Then for the next t lines, each test case consists of three inputs. The overs, current score and the target score.
Output
For each test case output the winning probability (in percentage) of the chasing team.
Note: The first two decimal places in its representation should be printed without rounding
.
Constraints
1 <= t <= 1000
0.0 <= Overs <= 20.0
0<= Score <= 300
0<= Wickets <= 10
Score <= Target <= 300
Example
Input:
10
19.4 129/9 129
20.0 100/10 100
19.5 0/9 100
19.5 0/0 1
0.0 0/0 300
0.0 0/0 200
0.0 0/0 100
10.0 0/0 100
10.0 0/5 100
13.5 112/4 222
Output:
100.00
100.00
0.00
80.00
18.02
61.65
97.60
97.60
55.49
35.84 | 32,847 |
I AM VERY BUSY (BUSYMAN)
I AM VERY BUSY
You are actually very busy man. You have a big schedule of activities. Your aim is to do as much as activities as possible.
In the given figure, if you go to date with crush, you cannot participate in the coding contest and you can’t watch the movie. Also if you play DotA, you can’t study for the exam. If you study for the exam you can’t sleep peacefully. The maximum number of activities that you can do for this schedule is 3.
Either you can
watch movie, play DotA and sleep peacefully (or)
date with crush, play DotA and sleep peacefully
Input Specifications
The first line consists of an integer
T
, the number of test cases. For each test case the first line consists of an integer
N
, the number of activities. Then the next
N
lines contains two integers
m
and
n
, the start and end time of each activity.
Output Specifications
For each test case find the maximum number of activities that you can do.
Input Constraints
1 <= T <=10
1 <= N <= 100000
0 <= start < end <= 1000000
Example
Sample Input: (empty lines just for clarity)
3
3
3 9
2 8
6 9
4
1 7
5 8
7 8
1 8
6
7 9
0 10
4 5
8 9
4 10
5 7
Sample Output:
1
2
3 | 32,848 |
VALIDATE THE MAZE (MAKEMAZE)
There are many algorithms to generate maze. (
maze generation algorithm
). After generating the maze we’ve to validate whether it’s a valid maze or not. A valid maze has exactly one entry point and exactly one exit point (exactly 2 openings in the edges) and there must be at least one path from the entry point to exit point.
Given a maze, just find whether the maze is "valid" or "invalid".
Input
The first line consists of an integer t, the number of test cases. Then for each test case, the first line consists of two integers m and n, the number of rows and columns in the maze. Then contains the description of the matrix M of order m×n. M[i][j] = # represents a wall and M[i][j] = '.' represents a space.
Output
For each test case find whether the maze is "valid" or "invalid".
Constraints
1 ≤ t ≤ 10000
1 ≤ m ≤ 20
1 ≤ n ≤ 20
Example
Input:
6
4 4
####
#...
#.##
#.##
5 5
#.###
#..##
##..#
#.#.#
###.#
1 1
.
5 1
#
#
.
.
#
2 2
#.
.#
3 4
#..#
#.##
#.##
Output:
valid
valid
invalid
valid
invalid
invalid | 32,849 |
GAMING ARENA (GAMARENA)
Elgin and Hajee are planning to conduct gamindrome next day. As they have to connect all the computers, they need LAN cables, hubs and wireless routers. They went to Richi street to purchase them. Unexpectedly hub was not available in any shop.
Any LAN cable can connect two computers. Any wireless router can connect at most ‘k’ number of computers. Any computer can be connected to at most one LAN cable and at most one wireless network. If a computer is connected to both LAN and wireless, the connections get automatically bridged.
They have n computers and their aim is to connect all the computers with minimum cost. So they have to buy minimum number of LAN cables and wireless routers.
The cost of of buying one LAN cable is L and the cost of buying one wireless router is W.
Given n, k, L and W find the minimum cost needed to connect all the computers.
Input
The first line contains an integer t, the number of test cases. Each test case consists 4 integers n, k, L and W as defined above.
Output
For each test case find the minimum cost to connect all the computers.
Constraints
1 <= t <= 1000
1 <= n <= 1000
2 <= k <= 1000
1 <= L <= 1000
1 <= W <= 1000
Example
Input:
9
1 4 8 6
10 2 5 8
5 4 9 9
2 5 2 6
7 3 3 6
3 3 3 5
6 4 7 2
10 4 2 7
5 3 10 8
Output:
0
57
18
2
18
5
11
20
26 | 32,850 |
Dominant Strings (DOMINST)
Given two strings
s
1
and
s
2
, we say that
s
1
dominates
s
2
if the (multi)set of characters in
s
1
is a proper superset of the (multi)set of characters in
s
2
. For instance, "acmicpc" dominates "camp", but it does not dominate "chimp" or "macpac". For a set
S
of strings, we call the strings in
S
which are not dominated by any string in
S
the
dominant strings
of
S
(even if they do not dominate any strings in
S
).
Now, your task is simply to find all the dominant strings of a set of strings.
Input
The input contains a single set of strings, with one string per line. Each string consists of at least one and at most ten lower-case alphabetic characters. There will be at most 15000 strings, and no two strings will be identical. Input is terminated by end-of-file.
Output
Output consists of all dominant strings in the input set, in alphabetical order, one word per line.
Example
Input:
acmicpc
cccp
macpac
chimp
camp
Output:
acmicpc
chimp
macpac | 32,851 |
Training (TRAIN07)
Mirko and Slavko are training hard for the annual tandem cycling marathon taking place in Croatia. They need to choose a route to train on.
There are N cities and M roads in their country. Every road connects two cities and can be traversed in both directions. Exactly N−1 of those roads are paved, while the rest of the roads are unpaved trails. Fortunately, the network of roads was designed so that each pair of cities is connected by a path consisting of paved roads. In other words, the N cities and the N−1 paved roads form a tree structure.
Additionally, each city is an endpoint for at most 10 roads total.
A training route starts in some city, follows some roads and ends in the same city it started in. Mirko and Slavko like to see new places, so they made a rule never to go through the same city nor travel the same road twice. The training route may start in any city and does not need to visit every city.
Riding in the back seat is easier, since the rider is shielded from the wind by the rider in the front. Because of this, Mirko and Slavko change seats in every city. To ensure that they get the same amount of training, they must choose a route with an even number of roads.
Mirko and Slavko's competitors decided to block some of the unpaved roads, making it impossible for them to find a training route satisfying the above requirements. For each unpaved road there is a cost (a positive integer) associated with blocking the road. It is impossible to block paved roads.
Write a program that, given the description of the network of cities and roads, finds the smallest total cost needed to block the roads so that no training route exists satisfying the above requirements.
Input
The first line of input contains two integers N and M (2 ≤ N ≤ 1 000, N−1 ≤ M ≤ 5 000), the number of cities and the total number of roads.
Each of the following M lines contains three integers A, B and C (1 ≤ A ≤ N, 1 ≤ B ≤ N, 0 ≤ C ≤ 10 000), describing one road. The numbers A and B are different and they represent the cities directly connected by the road. If C=0, the road is paved; otherwise, the road is unpaved and C represents the cost of blocking it.
Each city is an endpoint for at most 10 roads. There will never be more than one road directly connecting a single pair of cities.
Output
Output should consist of a single integer, the smallest total cost as described in the problem statement.
Example
Input:
5 8
2 1 0
3 2 0
4 3 0
5 4 0
1 3 2
3 5 2
2 4 5
2 5 1
Output:
5
Input:
9 14
1 2 0
1 3 0
2 3 14
2 6 15
3 4 0
3 5 0
3 6 12
3 7 13
4 6 10
5 6 0
5 7 0
5 8 0
6 9 11
8 9 0
Output:
48 | 32,852 |
A Summatory (PUCMM210)
f(n) is defined as: f(n) = 1
3
+2
3
+3
3
+...+n
3
, so it is the sum of the cubes of all natural numbers up to n.
In this problem you are about to compute,
f(1) + f(2) + f(3) + ... + f(n)
Input
The first line is an integer
T
(1 ≤
T
≤ 100,000), denoting the number of test cases. Then,
T
test cases follow.
For each test case, there is an integer
n
(1 ≤
n
≤ 1,000,000) written in one line.
Output
For each test case output the result of the summatory function described above.
Since this number could be very large, output the answer modulo 1,000,000,003.
Example
Input:
3
2
10
3
Output:
10
7942
46 | 32,853 |
E 23 Stairs pattern (PUCMM215)
In this problem you will work on a plane, where the natural numbers are arranged in a stair pattern.
Starting on coordinate (2, 1) through (2, 23) are the first 23 natural numbers in sequence, 1 is in (2,1), 2 is in (2,2) and so on..., the next 23 natural numbers (24 to 46) are arranged from (2, 24) through (24, 24), the next 23 from (25, 24) through (25, 46), a stair pattern where each step is 24 numbers high, this pattern continues infinitely.
Y-axis
| 48
| 24 25 26 27 . . . 46 47
| 23
| .
| .
| .
| 3
| 2
| 1
|_____________________________ X-axis
Input
You will be given a series of queries that could be one or two integers per line.
The last test case is 0 0.
each integer N, X
i
, Y
i
satisfy: 1 ≤ N, X
i
, Y
i
, ≤ 10
15
.
Output
If the test case is one integer you have to output two comma separated integers denoting the coordinates (x, y) of the selected number, if there are two numbers you have to output one integer that corresponds to the integer that is located in those coordinates, if there is no number with such coordinates, output the string "No Number"
Example
Input:
2
2 7
3 7
0 0
Output:
2, 2
7
No Number | 32,854 |
A Famous ICPC Team (TEAM2)
Mr. B, Mr. G, Mr. M and their coach Professor S are planning their way to Warsaw for the ACM-ICPC World Finals. Each of the four has a square-shaped suitcase with side length A
i
(1 ≤
i
≤ 4) respectively. They want to pack their suitcases into a large square box. The heights of the large box as well as the four suitcases are exactly the same. So they only need to consider the large box’s side length. Of course, you should write a program to output the minimum side length of the large box so that the four suitcases can be put into the box without overlapping.
Input
Each test case contains only one line containing 4 integers A
i
(1 ≤
i
≤ 4, 1 ≤ A
i
≤ 1,000,000,000) indicating the side length of each suitcase.
Output
For each test case, display a single line containing the case number and the minimum side length of the large box required.
Example
Input:
2 2 2 2
2 2 2 1
Output:
Case 1: 4
Case 2: 4
Explanation
For the first case, all suitcases have size 2×2. So they can perfectly be packed in a 4×4 large box without wasting any space.
For the second case, three suitcases have size 2×2 and the last one is 1×1. No matter how to rotate or move, you could find the side length of the box must be at least 4. | 32,855 |
A Famous Stone Collector (STONE2)
Mr. B loves to play with colorful stones. There are n colors of stones in his collection. Two stones with the same color are indistinguishable. Mr. B would like to select some stones and arrange them in line to form a beautiful pattern. After several arrangements he finds that it's very hard for him to enumerate all the patterns. So he asks you to write a program to count the number of different patterns.
Two patterns are considered different, if and only if they have different number of stones or have different colors on at least one position.
Input
Each test case starts with a line containing an integer n indicating the kinds of stones Mr. B have. Following this is a line containing n integers - the number of available stones of each color respectively. All the input numbers will be nonnegative and no more than 100.
Output
For each test case, display a single line containing the case number and the number of different patterns Mr. B can make with these stones, modulo 1,000,000,007, which is a prime number.
Example
Input:
3
1 1 1
2
1 2
Output:
Case 1: 15
Case 2: 8
Explanation
In the first case, suppose the colors of the stones Mr. B has are B, G and M, the different patterns Mr. B can form are: B; G; M; BG; BM; GM; GB; MB; MG; BGM; BMG; GBM; GMB; MBG; MGB. | 32,856 |
A Famous Equation (EQ2)
Mr. B wrote an addition equation such as 123+321=444 on the blackboard after class. Mr. G removes some of the digits and makes it look like “1?3+??1=44?”. After Mr. B realizes some digits are missing, he wants to recover them. Unfortunately, there may be more than one way to recover the equation. For example “1?3+??1=44?” can be recovered to “123+321=444” or “143+301=444” and many other possible solutions. Your job is to determine the number of different possible solutions.
Input
Each test case describes a single line with an equation like
a+b=c
which contains exactly one plus sign
+
and one equal sign
=
with some digits are missing and replaced with
?
. You may assume
a
,
b
and
c
are non-negative integers, and the length of each number is no more than 9. In the other words, the equation will contain three integers less than 1,000,000,000.
Output
For each test case, display a single line with its case number and the number of possible solutions to recover the equation.
Example
Input:
7+1?=1?
?1+?1=22
Output:
Case 1: 3
Case 2: 1
Explanation
There are three solutions for the first case:
7+10=17, 7+11=18, 7+12=19
There is only one solution for the second case:
11+11=22
Note that 01+21=22 is not a valid solution because extra leading zeros are not allowed. | 32,857 |
A Famous King’s Trip (TRIP2)
Mr. B is the chief engineer in the Kingdom of FDUCS. Recently, the King asks Mr. B to develop a new plan of the road network in the country, since the existing one is so old that traffic jam often occurs. Unfortunately, Mr. B is now preparing for the ICPC World Final Contest so that he is quite busy. He asks his friends, Mr. G and Mr. M to help him finish that work. When Mr. B gets the solution from his friends, he realizes some problems: Mr. B forgot to specify the budget plan to Mr. G and Mr. M, thus the new solution contains too many new roads which the government cannot afford. After a precise calculation, Mr. B finds that he has just to delete exactly two roads in term of the financial facts (Of course, Mr. B will not delete more than two roads because he wants people in his country to have a convenient traffic).
Can Mr. B delete two roads arbitrarily? The answer is negative. The King would like to take a travel on the new road system to review Mr. B's work. However, the King is so busy that he does not want to take travel with redundancy. That is, the King wants Mr. B to design a road system so that he can travel from the palace (in one city), pass each road exactly once, and then back to the palace. Moreover, during his travelling, the king must visit each city at least once too.
Mr. B feels hard to satisfy the Kings demand by deleting two roads from the original design. As an ICPC candidate with unlimited potential, can you help him?
Input
For each test case, the first line contains two integers,
n
and
m
(1 <=
n
,
m
<= 200,000), indicating the number of cities in the Kingdom and the roads in Mr. B's original plan. Following this are
m
lines, each contains a pair of integers
a
and
b
. Each of them denotes
a
bidirectional road between city
a
and city
b
(1 <=
a
,
b
<= n and
a
!=
b
), the number of cities are counted from 1. No two roads connect the same pair of cities.
Output
For each test case, if Mr. B can satisfy the Kings requirement, then output
YES
in the first line, otherwise, output
NO
. If the answer is
YES
, output two integers
X
and
Y
(
X
<
Y
) in the following line, specifying two roads that Mr. B should delete from the original design.
X
and
Y
are the indexes of roads in the input, counting from 1. If there are more than one possible answer, output the one that makes the pair of (
X
,
Y
) lexicographically smallest.
Example
Input:
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output:
Case 1: YES
1 6 | 32,858 |
The Famous ICPC Team Again (MEDIAN3)
When Mr. B, Mr. G and Mr. M were preparing for the 2012 ACM-ICPC World Final Contest, Mr. B had collected a large set of contest problems for their daily training. When they decided to take training, Mr. B would choose one of them from the problem set. All the problems in the problem set had been sorted by their time of publish. Each time Prof. S, their coach, would tell them to choose one problem within a particular publish time interval. That is to say, if problems had been sorted in a line, each time they will choose one of them from a specified segment of the line.
Moreover, when collecting the problems, Mr. B had also known an estimation of the difficulty of each problem. When he was asked to choose a problem, if he chose the easiest one, Mr. G would complain that “Hey, what a trivial problem!”; if he chose the hardest one, Mr. M would grumble that it took too much time to finish it. For addressing this dilemma, Mr. B decided to take the one with the medium difficulty. Therefore he needed a way to know the median number in the given interval of the sequence.
Input
For each test case, the first line contains a single integer
n
(1 <=
n
<= 100,000) indicating the total number of problems. The second line contains
n
integers
x
i
(0 <=
x
i
<= 1,000,000,000), separated by single space, denoting the difficulties of each problem, already sorted by publish time. The next line is a single integer
m
(1 <=
m
<= 100,000), specifying number of queries. Then m lines follow, each line contains a pair of integers,
A
and
B
(1 <=
A
<=
B
<=
n
), denoting that Mr. B needed to choose a problem between positions
A
and
B
(inclusively, positions are counted from 1). It is guaranteed that the number of items between
A
and
B
is odd.
Output
For each query, output a single line containing an integer which denotes the difficulty of the problem that Mr. B should choose.
Example
Input:
5
5 3 2 4 1
3
1 3
2 4
3 5
5
10 6 4 8 2
3
1 3
2 4
3 5
Output:
Case 1:
3
3
2
Case 2:
6
6
4 | 32,859 |
A Famous City (CITY2)
After Mr. B arrived in Warsaw, he was shocked by the skyscrapers and took several photos. But now when he looks at these photos, he finds in surprise that he isn't even able to point out the number of buildings in it. So he decides to work it out as follows:
divide the photo into n vertical pieces from left to right. The buildings in the photo can be treated as rectangles, the lower edge of which is the horizon. One building may span several consecutive pieces, but each piece can only contain one visible building, or no buildings at all.
measure the height of each building in that piece.
write a program to calculate the minimum number of buildings.
Mr. B has finished the first two steps, the remaining comes to you.
Input
Each test case starts with a line containing an integer
n
(1 ≤
n
≤ 100,000). Following this is a line containing
n
integers - the height of building in each piece respectively. Note that zero height means there are no buildings in this piece at all. All the input numbers will be nonnegative and less than 1,000,000,000.
Output
For each test case, display a single line containing the case number and the minimum possible number of buildings in the photo.
Example
Input:
3
1 2 3
3
1 2 1
Output:
Case 1: 3
Case 2: 2
Explanation
The possible configurations of the samples are illustrated below: | 32,860 |
Two Famous Companies (COMPANYS)
In China, there are two companies which offer the internet service for the people from all cities: China Telecom and China Unicom. They both are planning to build cables between cities. The government wants to connect all the cities in minimum costs of course. So the minister of finance Mr. B wants to choose some of the cable plans from the two companies and calculate the minimum cost needed to connect all the cities. Mr. B knows that there are
N
-1 cables should be built in order to connect all
N
cities of China. For some political reason, Mr. B should choose
K
cables from the China Telecom and the rest
N
-1-
K
cables from the China Unicom. Your job is to help Mr. B determine which cables should be built and the minimum cost to build them. You may assume that the solution always exists.
Input
Each test case starts with a line containing the number of cities
N
(1 <=
N
<= 50,000), number of cable plans
M
(
N
-1 <=
M
<= 100,000) and the number of required cables from China Telecom
K
(0 <=
K
<=
N
-1). This is followed by
M
lines, each containing four integers
a
,
b
,
c
,
x
(0 <=
a
,
b
<= N-1,
a
!=
b
, 1 <=
c
<= 100,
x
=[0,1]) indicating the pair of cities this cable will connect, the cost to build this cable and the company this cable plan belongs to.
x
=0 denotes this cable plan belongs to China Telecom and
x
=1 denotes this cable plan is from China Unicom.
Output
For each test case, display the case number and the minimum cost of the cable building plan.
Example
Input:
2 2 1
0 1 1 1
0 1 2 0
2 2 0
0 1 1 1
0 1 2 0
Output:
Case 1: 2
Case 2: 1
Explanation
In the first case, there are two cable plans between the only two cities, one from China Telecom and one from China Unicom. Mr. B needs to choose the one from China Telecom to satisfy the problem requirement even the cost is higher.
In the second case, Mr. B must choose the cable from China Unicom, which leads the answer to 1. | 32,861 |
A Famous Game (PRLGAME2)
Mr. B and Mr. M like to play with balls. They have many balls colored in blue and red. Firstly, Mr. B randomly picks up
N
balls out of them and put them into a bag. Mr. M knows that there are
N
+1 possible situation which the number of red balls are ranged from 0 to
N
, and we assume the possibilities of the
N
+1 situation are the same. But Mr. M does not know which situation occurs. Secondly, Mr. M picks up P balls out of the bag and examines them. There are
Q
red balls and
P
-
Q
blue balls. The question is, if he picks one more ball out of the bag, what is the possibility that this ball is red.
Input
Each test case contains only one line with three integers
N
,
P
and
Q
(2 ≤
N
≤ 100,000, 0 ≤
Q
≤
P
≤
N
-1).
Output
For each test case, display a single line containing the case number and the possibility of the next ball Mr. M picks out is red. The number should be round to four decimal places.
The judge is "ignoring extra whitespaces".
Example
Input:
3 0 0
4 2 1
Output:
Case 1: 0.5000
Case 2: 0.5000
Explanation
For example as the sample test one, there are three balls in the bag. The possibilities of the four possible situations are all 0.25. If there are no red balls in the bag, the possibility of the next ball are red is 0. If there is one red ball in the bag, the possibility is 1/3. If there are two red balls, the possibility is 2/3. Finally if all balls are red, the possibility is 1. So the answer is 0 * (1/4) + (1/3) * (1/4) + (2/3) * (1/4) + 1 * (1/4) = 0.5. | 32,862 |
A Famous Grid (SPIRALGR)
Mr. B has recently discovered the grid named "spiral grid". Construct the grid like the following figure. (The grid is actually infinite. The figure is only a small part of it.)
Considering traveling around it, you are free to any cell containing a composite number or 1, but traveling to any cell containing a prime number is disallowed. You can travel up, down, left or right, but not diagonally. Write a program to find the length of the shortest path between pairs of nonprime numbers, or report it's impossible.
Input
Each test case is described by a line of input containing two nonprime integer 1 <=
x
,
y
<=10,000.
Output
For each test case display its case number followed by the length of the shortest path or
impossible
in one line.
Example
Input:
1 4
9 32
10 12
Output:
Case 1: 1
Case 2: 7
Case 3: impossible | 32,863 |
With a Pit of Death (DOJO)
Leo is training his martial arts in byteland's dojo.
The dojo is a rectangular ( n × m ) area with a pit of death, a square located at (i, j), where 1 <= i <= n, and 1 <= j <= m.
Every night, battles are very hard and the dojo is destructed, and reconstructed during the day around the pit.
Every evening, Leo's first mission is to make in place tatamis (2 × 1) in the new dojo.
Tatamis should cover the whole dojo except the pit of death.
Sometimes it's possible, sometimes not!
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are four integers n, m, i and j.
Output
For each test case, print the answer of the problem : "Possible." or "Impossible.".
Example
Input:
2
3 3 2 2
3 3 1 2
Output:
Possible.
Impossible.
Constraints
1 <= T <= 1 000
1 <= i <= n <= 32
1 <= j <= m <= 10
2000
Edit 2017-02-11 : 0.15s as TL, alongside the compiler changes. | 32,864 |
Polynomial f(x) to Polynomial h(x) (POLTOPOL)
Given polynomial of degree d, f(x) = c
0
+ c
1
x + c
2
x
2
+ c
3
x
3
+ ... + c
d
x
d
For each polynomial f(x) there exists polynomial g(x) such that:
f(x) = g(x) - g(x - 1) for each integer x
g(0) = 0
Your task is to calculate polynomial h(x) = g(x) / x.
(Note : degree of polynomial h(x) = degree of polynomial f(x))
Input
The first line of input contain an integer T, T is number of test cases (0 < T ≤ 10
4
)
Each test case consist of 2 lines:
First line of the test case contain an integer d, d is degree of polynomial f(x) (0 ≤ d ≤ 18)
Next line contains d+1 integers c
0
, c
1
... c
d
, separated by space, represent the coefficient of polynomial f(x) (-2
31
< c
0
, c
1
... c
d
< 2
31
and c
d
≠ 0)
Output
For each test case, output the coefficient of polynomial h(x) separated by space. Each coefficient of polynomial h(x) is guaranteed to be an integer.
Example
Input:
5
0
13
1
-1 2
1
0 2
2
2 -5 9
3
23 9 21 104
Output:
13
0 1
1 1
1 2 3
31 41 59 26
Explanation
First Test Case
f(x) = 13
g(x) that satisfy: g(x) - g(x - 1) = f(x) = 13 and g(0) = 0 is: g(x) = 13x
h(x) = g(x)/x so h(x) = 13
output : 13
Second Test Case
f(x) = -1 + 2x
g(x) that satisfy: g(x) - g(x - 1) = f(x) = -1 + 2x and g(0) = 0 is: g(x) = x
2
h(x) = g(x) / x so h(x) = x = 0 + 1x
output : 0 1
Third Test Case
f(x) = 0 + 2x
g(x) that satisfy: g(x) - g(x - 1) = f(x) = 2x and g(0) = 0 is: g(x) = x + x
2
h(x) = g(x) / x so h(x) = 1 + 1x
output : 1 1
See also:
Another problem added by Tjandra Satria Gunawan | 32,865 |
The return of the Cake (REBOUND)
It is well known that, in byteland, when you throw a cake, the angle of reflection is not the angle of incidence. Measured from the ground, the angle is the double, in byteland!
You stand at point A(0, z), and you want to throw a cake in Leo's face. Leo stands at B(x, y) and is a very dangerous man, so you decide to use the ground in order to make your cake rebound.
Your shot is precise only if you can use an integer value t in the interval [0, x], in order to reflect on C(t, 0). Sometimes it's possible, sometimes not!
Input
The input begins with the number T of test cases in a single line. In each of the next T lines there are three integers x, y and z, explaining the locations : you A(0, z), Leo B(x, y).
Output
For each test case, find and print the only integer t such 0 <= t <= x, that allow this perfect shot. If it's not possible, output "Not this time.".
Example
Input:
3
5 4 1
6 5 2
7 3 1
Output:
2
Not this time.
3
Comment : the last case is the one illustrated above.
Constraints
1 < T < 100 000
0 < x < 1 000 000 000
0 < y < 1 000 000 000
0 < z < 1 000 000 000
Edit(2017-02-11) : New time limit (after compiler changes). | 32,866 |
Aho-Corasick Trie (AHOCUR)
The
Aho–Corasick string matching algorithm
is a
string searching algorithm
invented by
Alfred V. Aho
and
Margaret J. Corasick
. It is a kind of dictionary-matching algorithm that locates elements of a finite set of strings (the "dictionary") within an input text. It matches all patterns simultaneously.
The Algorithm described above, requires an input file generator. The generator generates a text of length
L
, by choosing
L
characters randomly. Probability of choosing each character is given as priori, and independent of choosing others. Now, given a set of patterns, calculate the probability of a valid program generating “no”.
Input
First line contains an integer
T
, the number of test cases. Each case starts with an integer
K
, the number of pattern strings. Next
K
lines each contain a pattern string, followed by an integer
N
, number of valid characters. Next
N
lines each contain a character and the probability of selecting that character,
p
i
. Next an integer
L
, the length of the string generated. The generated text can consist of only the valid characters, given above. There will be a blank line after each test case.
Output
For each test case, output the number of test case, and the probability of getting a “no”.
Constraints
T ≤ 100
K ≤ 40
Length of each pattern string is between 1 and 20
Each pattern string consists of only alphanumeric characters (‘a’ to ‘z’, ‘A’ to ‘Z’, ’0’ to ‘9’)
Valid characters are all alphanumeric characters
∑p
i
= 1
L ≤ 100
Example
Input
2
1
a
2
a 0.5
b 0.5
2
2
ab
ab
2
a 0.2
b 0.8
2
Output:
Case #1: 0.250000
Case #2: 0.840000 | 32,867 |
MAKESUM (MAKESUM)
Pairwise sums of n numbers (i.e. NC2 sums) are given in sorted order.
You need to identify the numbers and print then. If there are several solutions print the lexicographically smallest one.
The output should have natural numbers only.
Input
n ≤ 50
n numbers each ≤ 10
5
.
Output
The lexicographically smallest set of numbers.
Example
Input:
1
2
Output:
1 1
Input:
3
2 2 2
Output:
1 1 1
Input:
6
2 2 2 3 3 3
Output:
1 1 1 2
Input:
1
4
Output:
1 3
Here 2 2 and 3 1 are also possible solutions but we have to print the lexicographically smallest one. | 32,868 |
Counting diff-pairs (CPAIR2)
You are given sequence A of N integers. You are also given integer K and M queries. Each query consists of two integers l, r. For each query output number of pairs i, j such that l ≤ i < j ≤ r and abs(A[i] - A[j]) ≥ K.
Indexing starts with 1.
N ≤ 50000
M ≤ 50000
1 ≤ A[i] ≤ 100000
NOTE: All tests are randomly generated.
Input
First line of input contains integers N, M, K in this order.
Second line contains N integers representing array A.
Next M lines describe queries.
Output
Output answer for each query.
Example
Input:
3 1 2
1 2 3
1 3
Output:
1 | 32,869 |
A Summatory (HARD) (ASUMHARD)
f(n) is defined as: f(n) = 1
k
+2
k
+3
k
+ ... +n
k
, so it is the sum of the k-th power of all natural numbers up to n.
In this problem you are about to compute,
f(1) + f(2) + f(3) + ... + f(n)
Input
The first line is an integer
T
(1 ≤
T
≤ 54,321), denoting the number of test cases. Then,
T
test cases follow.
For each test case, there are two integers
n
(1 ≤
n
≤ 123,456,789) and
k
(0 ≤
k
≤ 321) written in one line, separated by space.
Output
For each test case output the result of the summatory function described above.
Since this number could be very large, output the answer modulo 1,234,567,891.
Example
Input:
5
2 3
10 3
3 3
100 0
100 1
Output:
10
7942
46
5050
171700
Warning: A naive algorithm may not run in time
See also:
Another problem added by Tjandra Satria Gunawan | 32,870 |
Wrong directions (WRONG)
Farmer John has just purchased a fancy new programmable tractor. To make the tractor move, he types in a string of length N (1 ≤ N ≤ 100,000) consisting of only the characters F, L, and R. Each 'F' instructs the tractor to move forward one unit, and the characters 'L' and 'R' result in left and right turns of 90 degrees, respectively. The tractor starts out at the origin (0, 0) facing north.
After programming his tractor by typing in his intended command string, FJ remembers that he typed exactly one character in the command string incorrectly, but he can't remember which one! For example, he might have typed 'F' or 'L' when his intended string contained the character 'R'. Please compute the number of different locations in the plane at which the tractor might end up as a result (the direction the tractor faces in its final location does not matter).
Input:
* Line 1: Farmer John's intended command string.
Output
* Line 1: The number of positions at which the tractor might end up, given that FJ mistypes one of the characters in his command string.
Example
INPUT:
FF
OUTPUT:
3
Explanation
Farmer John wants the tractor to advance forward twice, ideally ending at position (0, 2). There are 4 possible mistyped sequences: FL, FR, LF, an RF. These will land the tractor at (0, 1), (0, 1), (-1, 0), and (1, 0) respectively - a total of 3 distinct locations. | 32,871 |
Red Cross Hospital (REDCROSS)
The Red Cross is a humanitarian and neutral organization that strives to provide assistance to victims of civil wars and other situations of serious violence.
Recently, Nlogônia entered into a political crisis that culminated in a great civil war. This war wrecked dozens of innocent communities across the country. Seeing the calamity situation in which the country joined, the Red Cross decided to help the population in all affected regions in Nlogônia.
For this, it was decided that a hospital base will be installed to support the Red Cross in the country. However, the summit do not know where to build the base of Red Cross hospital. You and your team were hired to tell the Red Cross the position that they must build the hospital, with the constraint that the distance to the farthest community from the hospital is as small as possible.
Input
The input file consists of several test cases. For each test case, the first line contains the number of affected communities N to be served. Each of the following N lines contains a localization of each community. Localization is represented by decimal coordinates X and Y. After the first test case will be another line with a new test case defined by number of communities N. The input never contains repeated coordinates for each community in each test case and the input ends with N = 0.
Suppose:
0 ≤ N ≤ 100000
-100000 ≤ X, Y ≤ 100000
Output
For each test case of your program prints just a one line with two decimal number separated by commas indicating the optimum location for the construction of the base hospital, regardless of the area have a built space. Each coordinate must be printed with four decimal place of accuracy.
Example
Input:
2
-1 0
1 0
4
0.5 0.5
0.5 -0.5
0.0 0.5
0.0 -0.5
0
Output:
0.0000, 0.0000
0.2500, 0.0000 | 32,872 |
Boa viagem, Roim (ROIM)
Computer Engineering student Roim is getting ready for a trip to Mexico. For that, he has studied the airplane network, so he knows the details of all
R
regular flights currently in operation on all of the
N
available airports. Unfortunately, one of his school mates is very annoying and keeps saying the same stuff to him all the time.
To solve that issue, he will organize two different flight plans: one for the team and one for the annoying guy. The condition is that the flight plans may not contain the same flight (note that it is possible for both to pass through the same airport, and that the same flight may not be used by both even if the times are different). As this may not be possible using only regular flights, he has also considered using some of the
C
flights chartered by travel agencies, but he'd like to keep those to a minimum as they usually suffer from large delays. Of course, as long as the least number of chartered flights is picked, Roim will pick the plans with the least total cost (defined as the sum of the costs of all flights used).
Input
The input consists of several test cases. On the first line of a test case are three integers
N
(2 ≤ N ≤ 225),
R
and
C
(0 ≤ R+C ≤ N(N-1)/2) separated by spaces. The starting airport is 0, and the destination is N-1.
The next R lines contain integers
a
,
b
(0 ≤ a, b ≤ N-1),
c
(1 ≤ c ≤ 100), meaning that there exists a one-way regular flight between airports a and b, with cost c. The following C lines give details for chartered flights in the same manner. There is a blank line at the end of each test case. The last test case is followed by a line containing three zeros.
You may assume that any pair of cities is only connected in at most a single direction by a single flight.
Output
If it is possible to make the plans, print two integers separated by spaces. The first should be the minimum amount of chartered flights used, and the second is the total cost of the solution.
If it's impossible that both the team and the guy get to their destination, print "Boa viagem, Roim" instead.
Example
Input:
4 5 0
0 1 1
1 3 5
0 2 5
1 2 1
2 3 1
4 4 1
0 1 2
1 3 2
0 2 2
1 2 1
2 3 2
2 1 0
0 1 10
0 0 0
Output:
0 12
1 8
Boa viagem, Roim | 32,873 |
HELP ABHISHEK(version-II) (COMPLEX2)
ABHISHEK is weak of mathematics he is not able to solve the sequences frequently. So he invited topcoders to develop a program for solving the sequence. He managed to solve the other kind of sequences except one kind.
The sequence description is as follows:
(x-w)(x-w^2)(x-w^3)(x-w^4) ... (x-w^(n-1))
where x is a number and w is nth root of unity.
Input
first line contain number of test cases t. Then t line follow x and n. x and n separated by a space.
Constraints:
2 <= x <= 1000
2 <= n <= 1000
t <= 410
Output
Print the result per test case according to above sequence and also keep in mind if there is any term in decimal then write it in form of a fraction. see the I/O for further detail.
Example
Input:
1
5 10
Output:
9765624/4
Time limit is strict, so optimise your solution as you can. First try the tutorial version at
COMPLEX1 | 32,874 |
Prime Time (PTIME)
For your math homework this week your teacher gave you five large numbers and asked you to find their prime factors. However these numbers aren't
nearly
large enough for someone with knowledge of programming like yourself. So you decide to take the factorial of each of these numbers. Recall that N! (N factorial) is the product of the integers from 1 through N (inclusive). It’s your job now to create a program to help you do your homework.
Input
Each test case contains a number N (2 ≤ N ≤ 10000).
Output
The output should contain a line representing the prime factorization of the factorial given number, which should be of the form:
p
1
^e
1
* p
2
^e
2
* ... * p
k
^e
k
where p
1
, p
2
, ... p
k
are the distinct prime factors of the factorial of the given number in increasing order, and e
1
, e
2
, ... e
k
are their exponents.
Example
Input:
10
Output:
2^8 * 3^4 * 5^2 * 7^1 | 32,875 |
Teaming up for the competition (PONY5)
Since the Iron Pony competition was such fun last year, the ponies have decided to host a similar event this year, but this time it would be in teams. When each pony arrives at the event, they receive a number between 1 and 10^18. It is possible that some ponies receive the same number. Once every pony arrives, Miss Mayor will announce a number X and how to determine which team a pony is on - the pony takes their given number and looks at the result modulo X. That is their team number.
Dr. Whooves is at the event with a group, and he was wondering about the numbers X that would let his entire group be on the same team. Dr. Whooves likes big numbers, so he is going to suggest to Miss Mayor the number X which is the largest number that would let his entire group be on the same team.
Your goal is to determine what number Dr. Whooves suggested to Miss Mayor.
But because the number might be really big, if there is a valid X larger than 10^18, just print "I can't count that high".
Input
The input will contain one line with a number T, the number of test cases in the file.
On the next T lines, one for each of the cases. The format of the case is "Case #i: N a1 a2 ... aN" where N is the number of ponies in Dr. Whooves's group, and each a_j is the number given to a pony in his group.
Output
There will be T lines in your output, one for each of the test cases in the input. The output format for case i is "Case #i: X" where X is the number that Dr. Whooves suggests to Miss Mayor, unless X is too large, and then you print "I can't count that high" [see sample output]
Example
Input:
2
Case #1: 3 178 928 440
Case #2: 1 1000000000000000000
Output:
Case #1: 2
Case #2: I can't count that high
Limits
1 <= N <= 1000000 (10^6)
Warning: Large input files | 32,876 |
Kind and gently (RPLK)
Giselle is working on her house, as her husband won't be able to help in the task, she gently asks you for help, the task is very simple, Giselle wants to build some stairs that communicate two floors in the house. The stairs will be made of W segments of wooden, she is very confident on building the stairs, but she wants to build the stairs with some separation between steps. As you know, the end of a step is overlapped by the beginning of the other, and so on, between steps there are a single separation, as Giselle is very conservative, she wants to build the stairs using at most W segments of wood.
The image will help you to understand the task.
As you can see in the image, there is a single separation between each step relating to the height and the width of every step.
Giselle wants to build stairs using E pieces of wood that she wants to cut into at most W steps. You can only cut vertically and can't rotate the given pieces. Each step's width must be exactly M+1. M is the overlap and 1 is a constant width for placing feet.
Input
The first line of the test data will start with an integer T representing the T test cases, then, T cases will follow.
Each case starts with four positive integers (E, M, K, W) denoting E pieces of wood, M meters of overlap, K height of separator between each step and W, the maximum number of steps that can be cut out. Next, E lines will follow, each with two integers Eh and Ew representing respectively the height and the width of each piece of wood Giselle has.
Output
You must output the string "Scenario #i: " where i is the number of test case you're analyzing (starting at 1), followed by the maximum amount of height that you can possibly build.
Example
Input:
3
5 1 1 3
6 2
5 10
4 20
3 15
1 1
3 1 0 5
3 15
2 20
1 60
2 1 1 25
15 10
12 10
Output:
Scenario #1: 19
Scenario #2: 15
Scenario #3: 145
Explanation of the First Case
You can only cut the segment of width 6 into one piece, but the 5 segment of width 10 you can cut it into 5 pieces, as you only need 3 pieces to use, the maximum height will be of 6+5+5+3 = 19
Constraints
(1 <= Width and Height of each wooden piece <= 1000) = "WiHi".
Small input (40%)
1<= T <= 200
1<= {E, K, M} <= 100
WiHi <= M <= 100
1<= W <=100
Large Input (60%)
1 <= T <= 10
1 <= {E, K} <= 100,000
WiHi <= M <= 1,000
1 <= W <= 10,000 | 32,877 |
Lifesavers (RPLL)
German is the chief of the Rescuers and Principal Lifesavers of the ocean (RPL), he is in charge of commanding the search of survivors on a range given after a ship sinks, this range is established from the time that the ship sunk, he will always know this value, because he is magnificent in maths, however, he isn't good calculating the perfect searching range, this causes problem in rescuing survivors as the ship may exceed the limit of the area of searching.
It is known that German will always send three ships to make the rescue effective, as he can't send all his ships, he wants to maximize the area of the three ships covers. The ships of German aren't sophisticated, so they will be going on a single direction (always) and a constant speed. The ships moves every unit of time.
We say that an area is covered when the area made by the three points (triangular area) is lesser or equal than the maximum area that German knows.
German will give you the initial coordinates of all three ships (given in 2D), the direction the ship will be going and the speed per hour. The direction of the rescuer ship will always be to north, south, east or west and the maximum area of search. Please have in count that the area covered by the three ships must NOT exceed the area that German gives to you.
Input
The first line of the test data will start with an integer T representing the T test cases, then, T×4 Lines will follow, each of the following lines will contain, respectively, the maximum area of searching, the next three lines will contain, each, three integers and a string, denoting the coordinates the ship is in, the direction and the speed.
Output
You must output the string “Scenario #i: “ where i is the number of test case you're analyzing, followed by the time that
the three ships will cover the maximum possible area (without exceeding it). Time will always be discrete.
Example
Input:
2
150
1 4 north 2
2 0 south 2
3 1 east 2
12
0 -2 north 1
0 0 north 2
0 0 east 3
Output:
Scenario #1: 5
Scenario #2: 2
Explanation of the second sample
At hour two, the ship 1 will be at position (0, 0), the ship 2 will be at position (0, 4) and the ship 3 will be in (6, 0), computing the area of a triangle, we will have a value of 12, as we know that there is no other possible area that satisfies the maximum without exceeding it, we output 2.
It is guaranteed that all three ships will always be distancing themselves, then, the next area will always be bigger.
Constraints
1 ≤ T ≤ 100
-10
6
≤ X, Y ≤ 10
6
1 ≤ Speed ≤ 10
Small Input (30%)
For the “small” input, the triangles will always be rectangled triangles, making the area of them easier to calculate.
1 ≤ Max_Area_Of_Searching ≤ 10
3
Large Input (70%)
Points will form any triangle, time-limit is heavier on these files.
10
3
≤ Max_Area_Of_Searching ≤ 10
9 | 32,878 |
Mountain Cave (RPLM)
Charlie is picking some precious stones in a cave, this cave is known worldwide by the stones in it, however, this cave is very delicate and the minimum movement causes an instant collapse, Charlie knows the times that the tunnels will be free (as the instant collapses can free some tunnels) or covered by a pile of stones.
In his backpack, Charlie has some magical hammers that he carries for emergency, in some expeditions he won't have these hammers, but in others he will. The hammer causes an instant opening of any pile of stones blocking his way.
It is also known that Charlie travels some distance
d
in a time
t
from room
i
to room
j
, and the tunnel connecting them will be free from time
x
to time
y
. Charlie can return whenever he wants, so, traveling from room
j
to room
i
will be symmetric.
Charlie doesn't have infinite hammers, so, when he use one, the hammer will break, making it useless.
In addition, if Charlie knows that the tunnel will open in a time X, he can choose to stay until the path opens or use a magical hammer to go through the tunnel.
Given that information, your task is to find the minimum time with the minimum distance that Charlie can go from the entrance (0) to the center of the cave (V-1)
Input
The first line of the test data will start with an integer T representing the T test cases, then, T cases will follow, each of the cases starts with three integers, V E and M, denoting, respectively, the number of the rooms on the cave, the numbers of tunnels in the cave and the number of hammers Charlie will carry, the next E lines will contain six integers, denoting, respectively, the origin room
i
, the destiny room
j
, opening time
x
, collapse time
y
, distance
z
, and time
t
.
Output
You must output the string "Scenario #i: " where i is the number of test case you're analyzing, followed by the minimum time and the minimum distance associated to it, if Charlie isn't able to arrive to the V-1 room, output -1.
Example
Input:
4
6 6 2
0 1 1 18 3 3
0 2 1 12 4 4
0 4 1 3 5 5
2 3 1 8 2 2
3 4 1 5 3 3
4 5 5 20 1 1
6 6 1
0 1 1 18 3 3
0 2 1 12 4 4
0 4 1 3 5 5
2 3 1 8 2 2
3 4 1 5 3 3
4 5 5 20 1 1
6 6 0
0 1 1 18 3 3
0 2 1 12 4 4
0 4 1 3 5 5
2 3 1 8 2 2
3 4 8 25 3 3
4 5 5 20 1 1
3 3 0
0 1 0 5 4 4
1 2 0 5 2 2
0 2 0 5 6 6
Output:
Scenario #1: 6 6
Scenario #2: 7 6
Scenario #3: 12 10
Scenario #4: -1
Constraints
1 <= T <= 10
Small input: (20%)
2 <= V <= 10
1 <= E <= 30
M = 0
Medium input: (30%)
2 <= V <= 100
1 <= E <= 1,000
M = 0
Large input: (50%)
2 <= V <= 100
1 <= E <= 1,000
0 <= M <= 50
It is guaranteed that the distance of the tunnels won't never exceed 10.
1 <= opening and collapse times <= 100,000
Clarifications
: You start with time 0. It will be always true that the time x will be lesser or equal than time y. While passing through a tunnel from room i to room j, if the tunnel collapses while you're inside, you can use a hammer to break through, otherwise that path is impossible to take. | 32,879 |
Negative Score (RPLN)
Orianna is a great swimmer and she's going to a swimming competition this month and needs your help as she is highly paranoic about the results of the competition.
The competition consists in some sort of evaluations, every judge makes a score and, based on that score and the score of other contestants she will get a score belonging to her results, those scores are final, meaning that will not change in the competition.
Orianna requires this solution with urgency, she is getting evaluated on a lot of ways and she is very worried about her results, so she wants to know what is the worst score from an evaluation A to other evaluation B inclusive.
Input
The first line of the test data will start with an integer T representing the T test cases, then, T cases will follow, each of the cases starts with two integers N and Q, denoting the number of evaluations Orianna had, then, N integers will follow denoting the score on each evaluation, after that, Q queries will begin, each query consist on two integers A and B.
Output
You must output the string “
Scenario #i:
“, a blank line and then the result of each query, remember, Orianna is interested on the worst score from evaluation A to evaluation B inclusive.
Example
Input:
2
5 3
1 2 3 4 5
1 5
1 3
2 4
5 3
1 -2 -4 3 -5
1 5
1 3
2 4
Output:
Scenario #1:
1
1
2
Scenario #2:
-5
-4
-4
Constraints
1 <= T <= 100
Small input (30%):
1 <= N <= 1,000
1 <= Q <= 1,000
-10^9 <= Ni <= 10^9
1 <= A <= B <= N
Large input (70%):
1 <= N <= 100,000
1 <= Q <= 100,000
-10^9 <= Ni <= 10^9
1 <= A <= B <= N
Solutions rejudged due to weak test cases. | 32,880 |
Easy Sequence! (SEQAGAIN)
Your task is to find the n
th
term of the following sequence :
F(n) = [F(n-1)*F(n-2)]
K
for n>1
F(0), F(1), n and K will be provided as input.
Modulus for all calculations is 1000000007.
You should print the answer modulo 1000000007 i.e. F(n)%1000000007
Input
Input starts with a line containing an integer T ≤ 5000 which is the number of test cases in the file. Your program will be run on several input files.
Each test case consists of four space separated integers : F(0), F(1), n and K.
Output
T lines containing one integer each, corresponding to the answers for the T test cases.
Constraints
0 ≤ n ≤ 10
18
0 ≤ K ≤ 10
9
0 ≤ F(0), F(1) ≤ 10
6
Example
Input:
1
1 1 2 1
Output:
1 | 32,881 |
Aliens at the subway (ALIEN3)
The female Alien moved to the biggest city in the world, this city has a giant subway system, this subway is always full of people, the Alien doesn't want to see humans and she wants to stay the least time possible in the subway system.
Preventing this scenario, the Alien brought from her planet some interesting and very rare objects, she calls this objects “Portable Teleporters”, with these objects the alien is on the capacity to teleport and ignore the next K stations, as you may know, this objects are limited and it can be used once.
As the city is so big that the subway is always full, she wants to stay the least number stations as possible, the Alien will start from station 0, wishing to go up to an station L, the subway is formed by N+1 (0 through N) stations and the Alien has K “Portable Teleporters”.
When the Alien uses a “Portable Teleporters” she will be teleported immediately to the I+Kj station, being I the station the alien was on and Kj the value of the Portable Teleporter.
If she is unable to use a teleporter or is better for her to go into the next station using the subway, she can do it, however, she can only move forward, NEVER backwards, furthermore, the Alien may not leave the limits of the stations (that means she can't go to any station before station 0 or any station after station N).
As you may know, the Alien doesn't wants to see a large number of people, to prevent this, she wants to visit as maximum T stations, if she can't reach her destination on T stations, she will simply exit the subway and will start walking on the city.
Your task is simple, given the N stations, the K objects and their values and the station the Alien wants to go, the L station the alien wants to go and the T number of tries, output the least stations visited so she can reach her destination.
Input
The Input will start with an integer P denoting the test cases, then P cases will follow, each case have three lines, the first line contains two integers N and K, denoting the N stations and the K portable teleporters, next line will contain K integers, denoting the value of each teleporter, the last line for each case will contain two integers L and T, that it will be the last station the alien wants to go and the T number of stations she wants to visit as maximum.
Output
The output will consists on P lines, each line containing the string "Scenario #i: " where i is the test case you're analyzing (starting by 1), followed by the minimum stations visited by the Alien to reach her destination, if she can't reach her destination on maximum T stations, print -1.
Sample
Input:
4
12 6
1 3 4 1 2 -2
10 10
12 6
1 3 2 1 2 -2
10 10
10 2
6 -2
5 10
10 2
1 1
10 5
Output:
Scenario #1: 4
Scenario #2: 6
Scenario #3: 3
Scenario #4: -1
Explanation of the first test case:
She teleports from station 0 to station 4 using the third teleporter, from 4 to 7 using the second teleporter, from 7 to 9 using the fifth teleporter and she can either walk to the next station or use another teleporter.
Explanation of the last case:
She can't reach the station 10 going through only 5 stations, the answer should be then -1.
Constraints
1 <= P <= 50
1 <= N <= 100
1 <= K <= 17
-100 <= Ki <= 100
0 <= L <= N
1 <= T <= 50 | 32,882 |
Max 2214 (MAX2214)
Max2214 is a game that consists of a board of
R
rows and
C
columns and two kinds of blocks: Some of the blocks are 2 cells high and 2 cells wide, the others are 1 cell high and 4 cells wide. Some of the cells of the board might be marked. The objective of the game is to place the most blocks on top of the board in a way that the blocks are aligned to the rows and columns, no pair of blocks overlap, marked cells do not contain any block, and the 1×4 blocks are placed horizontally exclusively. Also, blocks must be completely inside the board.
Input
The input consists in a single test.
The test case begins with 2 integers
R
and
C
in a single line: (1 ≤
R
≤ 52) (1 ≤
C
≤ 22).
The next
R
lines contain
C
characters. Each character represents a cell. If a character is X, it means the cell is a marked cell. If the character is '.' (a dot character) it means the cell is not marked.
Output
Show a single line containing the maximum quantity of blocks that can be placed in the board following the rules mentioned above.
Example
Input:
4 5
X....
X..XX
X..XX
....X
Output:
3 | 32,883 |
Count weighted paths (CNTPATHS)
John likes to take a walk from his house to university. He needs to arrive his university in at most
T
seconds after leaving his home. We can represent the situation as a
N
vertices graph. Vertex 0 of the graph will be John's home and vertex 1 John's university. There can be bidirectional roads connecting pairs of vertices, each road will take John some seconds to cross.
John likes variety. We consider a valid path to be a sequence of vertices that starts with vertex 0 (John's house) and finishes with vertex 1 (The University) and there exists a road connecting each pair of consecutive vertices in the sequences (Note that a vertex may appear multiple times in the path). The total time John needs to traverse a path is equal to the sum of the times needed to cross each individual road in it. Please count the total number of different paths that need at most
T
minutes to be traversed in total. Two paths are different if there is at least one moment at which they visit different vertices.
Given
T
,
N
and the roads between the vertices, ¿How many different paths that need at most
T
seconds exist? Print the result modulo 1000000007 (10
9
+7).
Input
The first line consists of a integer
TOTAL
, the total number of test cases (1 <=
N
<= 10).
Each of the following test cases begins with a single line that contains two integers :
N
and
T
. (2 <=
N
<= 5), (1 <=
T
<= 1000000000 (10
9
)).
The
N
following lines are indexed from
i
=0 to
N
-1. The
i-th
line will represent the roads that connect vertex
i
with other vertices. The line will consist of
N
character indexed from
j=
0 to
N
-1
.
The
j
-th character of the
i
-th line represents the road connecting vertex
i
with vertex
j
. If the character is '-', this means no road connects vertices
i
and
j
. Otherwise, the character will be a digit equal to 1,2 or 3, determining the number of minutes it takes John to move between vertices
i
and
j
.
For every pair (
i
,
j
), the road character between
i
and
j
will be the same as the one between
j
and
i
.
For each
i
, there will never be a road connecting vertex
i
with itself.
Vertex 0 represents John's house and Vertex 1 John's university.
Output
For each test case, show in a single line: "Case #i: R", where R is the total number of valid paths between vertices 0 and 1 that need at most
T
seconds.
Example
Input:
3
2 9
-3
3-
5 4
--123
--123
11---
22---
33---
3 100
-21
2-3
13-
Output:
Case #1: 2
Case #2: 4
Case #3: 924247768
Notes
There are two paths in the first case that need 9 minutes or less:
0 → 1 (3 minutes)
0 → 1 → 0 → 1 (9 minutes)
The second case contains 4 paths that need at most 4 minutes to be traversed:
0 → 2 → 1 (2 minutes)
0 → 3 → 1 (4 minutes)
0 → 2 → 0 → 2 → 1 (4 minutes)
0 → 2 → 1 → 2 → 1 (4 minutes)
0 → 4 → 1 is a path that needs 6 minutes. | 32,884 |
Eko (EKO)
Lumberjack Mirko needs to chop down
M
metres of wood. It is an easy job for him since he has a nifty new woodcutting machine that can take down forests like wildfire. However, Mirko is only allowed to cut a single row of trees.
Mirko‟s machine works as follows: Mirko sets a height parameter
H
(in metres), and the machine raises a giant sawblade to that height and cuts off all tree parts higher than
H
(of course, trees not higher than
H
meters remain intact). Mirko then takes the parts that were cut off. For example, if the tree row contains trees with heights of 20, 15, 10, and 17 metres, and Mirko raises his sawblade to 15 metres, the remaining tree heights after cutting will be 15, 15, 10, and 15 metres, respectively, while Mirko will take 5 metres off the first tree and 2 metres off the fourth tree (7 metres of wood in total).
Mirko is
ecologically
minded, so he doesn‟t want to cut off more wood than necessary. That‟s why he wants to set his sawblade as high as possible. Help Mirko find the
maximum integer height
of the sawblade that still allows him to cut off
at least M
metres of wood.
Input
The first line of input contains two space-separated positive integers,
N
(the number of trees, 1 ≤
N
≤ 1 000 000) and
M
(Mirko‟s required wood amount, 1 ≤
M
≤ 2 000 000 000).
The second line of input contains
N
space-separated positive integers less than 1 000 000 000, the heights of each tree (in metres). The sum of all heights will exceed
M
, thus Mirko will always be able to obtain the required amount of wood.
Output
The first and only line of output must contain the required height setting.
Example
Input:
4 7
20 15 10 17
Output:
15
Input:
5 20
4 42 40 26 46
Output:
36 | 32,885 |
DOJO Corridor I (DOJ1)
There's a long rectangular corridor in the hall's dojo, one place is already taken by a magic hanjō (1×1 square). You have to put tatamis (1×2 rectangle) in order to cover exactly the rest of the corridor. Sometimes it's possible, sometimes not!
Input
The input begins with the number T of test cases in a single line. In each of the next T lines there are two integers : N, M the size of the corridor, I,J coordinates of the magic hanjō, and K the modulo for the output.
Output
For each test case, print the number of possibility to do the job, modulo K.
Example
Input:
3
1 3 1 3 100
2 3 2 2 100
3 7 1 3 100
Output:
1
0
56
Constraints
1 <= T <= 30000
1 <= N <= 4
1 <= M <= 10^9
1 <= I <= N
1 <= J <= M
1 <= K <= 10^9
Uniform, independent, random input in the range.
Time limit is set to allow one half kB of python3 code to get AC.
Edit(19/I/2015, after cluster switch) : now my old code ends in 0.16s using PY3.4.
Edit(11-2-2017, after compiler update) : new TL. My old code ends in 0.09s using PY3.5. | 32,886 |
DOJO Corridor II (DOJ2)
There's a 5×N rectangular corridor in the hall's dojo, one place is already taken by a magic hanjō (1×1 square).
You have to put tatamis (1×2 rectangle) in order to cover exactly the rest of the corridor.
Sometimes it's possible, sometimes not!
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are an integer N the H-length of the corridor,
and I, J the coordinates of the magic hanjō. See sample input for details format.
Output
For each test case, print the number of possibility to do the job, modulo 1000000007.
Example
Input:
3
1 C 1
3 B 2
5 A 1
Output:
1
8
192
Constraints
1 <= T <= 40 000
1 <= N <= 20 000
A <= I <= E
1 <= J <= N
Uniform, independent, random input in the range. Input had been 'filtered' to let only possible configurations.
You may try too :
Grid Tiling
, or
Blocks for kids
Edit(19/I/2015, after cluster switch) : now my old code ends in 0.23s using PY3.4.
Edit(11-2-2017, after compiler update) : now my old code ends in 0.10s using PY3.5. New TL. | 32,887 |
Sum of Squares with Segment Tree (SEGSQRSS)
Segment trees are extremely useful. In particular "Lazy Propagation" (i.e.
see here, for example
) allows one to compute sums over a range in O(lg(n)), and update ranges in O(lg(n)) as well. In this problem you will compute something much harder:
The sum of squares over a range with range updates of 2 types:
1) increment in a range
2) set all numbers the same in a range.
Input
There will be
T
(
T
<= 25) test cases in the input file. First line of the input contains two positive integers,
N
(
N
<= 100,000) and
Q
(
Q
<= 100,000). The next line contains
N
integers, each at most 1000. Each of the next
Q
lines starts with a number, which indicates the type of operation:
2
st nd
-- return the sum of the squares of the numbers with indices in [
st
,
nd
] {i.e., from
st
to
nd
inclusive} (1 <=
st
<=
nd
<=
N
).
1
st nd x
-- add "x" to all numbers with indices in [
st
,
nd
] (1 <=
st
<=
nd
<=
N
, and -1,000 <=
x
<= 1,000).
0
st nd x
-- set all numbers with indices in [
st
,
nd
] to "
x
" (1 <=
st
<=
nd
<=
N
, and -1,000 <=
x
<= 1,000).
Output
For each test case output the
“Case <caseno>:”
in the first line and from the second line output the sum of squares for each operation of type 2. Intermediate overflow will not occur with proper use of 64-bit signed integer.
Example
Input:
2
4 5
1 2 3 4
2 1 4
0 3 4 1
2 1 4
1 3 4 1
2 1 4
1 1
1
2 1 1
Output:
Case 1:
30
7
13
Case 2:
1 | 32,888 |
Binary Sequence of Prime Number (BSPRIME)
Binary Sequence of Prime Number is a binary sequence that created by converting prime number to base-2 (without leading zeros):
(2)
10
=(10)
2
(3)
10
=(11)
2
(5)
10
=(101)
2
(7)
10
=(111)
2
...
If all base-2 of prime number joined, then we get the binary sequence like this: 10111011111011110110...
Now your task is to count how many digit '1' appear in the first
N
terms of the sequence, example:
If N=3, digit '1' appear 2 times:
1
0
1
110...
If N=10, digit '1' appear 8 times:
1
0
111
0
1111
101...
Input
The first line is an integer
T
(1 ≤
T
≤ 50,000), denoting the number of test cases. Then,
T
test cases follow.
For each test case, there is an integer
N
(0 ≤
N
≤ 150,000,000) written in one line.
Output
For each test case, output the number of digit '1' appear in the first
N
terms of the sequence
Example
Input:
3
3
10
50
Output:
2
8
36
See also
:
Another problem added by Tjandra Satria Gunawan | 32,889 |
Power with Combinatorics (POWPOW)
Your task is to find a
exp
b
,
a: Provided in input, 0 ≤ a ≤ 10
5
b: Provided in Input, 0 ≤ b ≤ 10
5
exp = (nC0)
2
+ (nC1)
2
+ (nC2)
2
+ ... + (nCn)
2
,
n: Provided in the input, 0 ≤ n ≤ 10
5
As the answer can be too large, you need to output modulo 10
9
+7.
nCr denotes n choose r.
Input
The first line of each input file contains number of test cases t (t ≤ 1000).
Then follow a new line.
Then follow t lines, each containing 3 integers, (i.e. a b n in order) each of them separated by a space.
Output
Output Contains t lines, ith line contains the answer of the ith test case .
Example
Input:
1
1 1 1
Output:
1
Explanation
In First test case, the Value of exp is 2, value of 1
2
1
is 1, so output is 1.
Click here to see my set of problems at Spoj. | 32,890 |
Power with Combinatorics(HARD) (POWPOW2)
Your task is to calculate a^(b^(exp)).
a: provided in input, 10^5 >= a >= 0
b: provided in input, 10^5 >= b >= 0
exp = (nC0)^2 + (nC1)^2 + (nC2)^2 + ... +(nCn)^2
n: provided in input, 10^5 >= n >= 0
Note: The Output for 0^0 should be 1.
nCr denotes n choose r.
As the answer can be too large, you need to output modulo 10^9+7.
Input
The first line of each input file contains number of test cases t (t<=1000).
Then follow a new line.
Then follow t lines, each containing 3 integers, (i.e. a b n in order) each of them separated by a space.
Output
Output contains t lines, ith line contains the answer of the ith test case.
Example
Input:
1
1 1 1
Output:
1
Explanation
In First test case, the Value of exp is 2, value of 1^(1^2) is 1, so output is 1.
Note: First try out the tutorial version where limits are low.
POWRTU
Click
here
to see my set of problems at SPOJ. | 32,891 |
Captain Qs Treasure (FUKU11G)
English
Vietnamese
You got an old map, which turned out to be drawn by the infamous pirate "Captain Q". It shows the locations of a lot of treasure chests buried in an island.
The map is divided into square sections, each of which has a digit on it or has no digit. The digit represents the number of chests in its 9 neighboring sections (the section itself and its 8 neighbors). You may assume that there is at most one chest in each section.
Although you have the map, you can't determine the sections where the chests are buried. Even the total number of chests buried in the island is unknown. However, it is possible to calculate the minimum number of chests buried in the island. Your mission in this problem is to write a program that calculates it.
Input
The input is a sequence of datasets. Each dataset is formatted as follows. h w map The first line of a dataset consists of two positive integers h and w. h is the height of the map and w is the width of the map. You may assume 1 <= h <= 15 and 1 <= w <= 15.
The following h lines give the map. Each line consists of w characters and corresponds to a horizontal strip of the map. Each of the characters in the line represents the state of a section as follows.
'.': The section is not a part of the island (water). No chest is here.
'*': The section is a part of the island, and the number of chests in its 9 neighbors is not known.
'0' .. '9': The section is a part of the island, and the digit represents the number of chests in its 9 neighbors.
You may assume that the map is not self-contradicting, i.e., there is at least one arrangement of chests. You may also assume the number of sections with digits is at least one and at most 15. A line containing two zeros indicates the end of the input.
Output
For each dataset, output a line that contains the minimum number of chests. The output should not contain any other character.
Example
Input:
5 6
*2.2**
..*...
..2...
..*...
*2.2**
6 5
.*2*.
..*..
..*..
..2..
..*..
.*2*.
5 6
.1111.
**...*
33....
**...0
.*2**.
6 9
....1....
...1.1...
....1....
.1..*..1.
1.1***1.1
.1..*..1.
9 9
*********
*4*4*4*4*
*********
*4*4*4*4*
*********
*4*4*4*4*
*********
*4*4*4***
*********
0 0
Output:
6
5
5
6
23 | 32,892 |
Round Trip (FUKU11J)
English
Vietnamese
Jim is planning to visit one of his best friends in a town in the mountain area. First, he leaves his hometown and goes to the destination town. This is called the go phase. Then, he comes back to his hometown. This is called the return phase. You are expected to write a program to find the minimum total cost of this trip, which is the sum of the costs of the go phase and the return phase.
There is a network of towns including these two towns. Every road in this network is one-way, i.e., can only be used towards the specified direction. Each road requires a certain cost to travel.
In addition to the cost of roads, it is necessary to pay a specified fee to go through each town on the way. However, since this is the visa fee for the town, it is not necessary to pay the fee on the second or later visit to the same town.
The altitude (height) of each town is given. On the go phase, the use of descending roads is inhibited. That is, when going from town
a
to
b
, the altitude of
a
should not be greater than that of
b
. On the return phase, the use of ascending roads is inhibited in a similar manner. If the altitudes of
a
and
b
are equal, the road from
a
to
b
can be used on both phases.
Input
The input consists of multiple datasets, each in the following format.
n m
d
2
e
2
d
3
e
3
.
.
.
d
n-1
e
n-1
a
1
b
1
c
1
a
2
b
2
c
2
.
.
.
a
m
b
m
c
m
Every input item in a dataset is a non-negative integer. Input items in a line are separated by a space.
n
is the number of towns in the network.
m
is the number of (one-way) roads. You can assume the inequalities 2 ≤
n
≤ 50 and 0 ≤
m
≤
n
(
n
−1) hold. Towns are numbered from 1 to
n
, inclusive. The town 1 is Jim's hometown, and the town
n
is the destination town.
d
i
is the visa fee of the town
i
, and
e
i
is its altitude. You can assume 1 ≤
d
i
≤ 1000 and 1≤
e
i
≤ 999 for 2≤
i
≤
n
−1. The towns 1 and
n
do not impose visa fee. The altitude of the town 1 is 0, and that of the town n is 1000. Multiple towns may have the same altitude, but you can assume that there are no more than 10 towns with the same altitude.
The
j
-th road is from the town
a
j
to
b
j
with the cost
c
j
(1 ≤
j
≤
m
). You can assume 1 ≤
a
j
≤
n
, 1 ≤
b
j
≤
n
, and 1 ≤
c
j
≤ 1000. You can directly go from
a
j
to
b
j
, but not from
b
j
to
a
j
unless a road from
b
j
to
a
j
is separately given. There are no two roads connecting the same pair of towns towards the same direction, that is, for any
i
and
j
such that
i
≠
j
,
a
i
≠
a
j
or
b
i
≠
b
j
. There are no roads connecting a town to itself, that is, for any
j
,
a
j
≠
b
j
.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, a line containing the minimum total cost, including the visa fees, of the trip should be output. If such a trip is not possible, output “-1”.
Example
Input:
3 6
3 1
1 2 1
2 3 1
3 2 1
2 1 1
1 3 4
3 1 4
3 6
5 1
1 2 1
2 3 1
3 2 1
2 1 1
1 3 4
3 1 4
4 5
3 1
3 1
1 2 5
2 3 5
3 4 5
4 2 5
3 1 5
2 1
2 1 1
0 0
Output:
7
8
36
-1 | 32,893 |
Jobs (POSAO)
Little Domagoj has hands full of work. His jobs are organized in
NxN
matrix such that each cell represents one job. He can start doing job at cell (x, y) if and only if jobs at cells (x, y-1) and (x-1, y) are done (if they exist).
On the picture required jobs are shown for grey cells.
Domagoj has
K
computers which he will use for doing jobs. One computer is able to do at most one job in one second. Also, all computers need not to be used all the time. Help Domagoj and organize order in which computers will do jobs in least possible time.
Input
In the first line there are two integers
N
and
K
(1 ≤
N
,
K
≤ 10
9
)
Output
Print least possible time in which all jobs can be done.
Example
Input:
3 2
Output:
6
Input:
5 1
Output:
25
Input:
4 4
Output:
7 | 32,894 |
Drawing Triangles with Brainf##k (BFTRI)
Your task is just to draw triangles! seems easy(?) but only
Brainf**k programming language
is allowed.
Input
The first line is an integer
T
(0 <
T
< 100), denoting the number of test cases. Then,
T
lines follow.
For each test case, there are one character
c
(ASCII(32) <
c
< ASCII(127)) and one integer
i
(0 <
i
< 100) written in one line, separated by a space. Each line end with ASCII(10).
Output
For each test case, output triangle size
i
(draw triangle using character
c
). See example.
Example
Input:
3
& 1
@ 3
? 5
Output:
&
@
@@
@@@
?
??
???
????
?????
See also:
Another problem added by Tjandra Satria Gunawan | 32,895 |
DONALDO (DONALDO)
Donaldo is a great footballer. Since he is famous, he has lots of girlfriends. But the problem is, he isn't certain about the actual number of his girlfriends. So, he checked his mobile inbox. His girlfriends send him a lot of texts. But he knows that, none of them will send more than 1 text between
I
seconds of time interval. Given the exact times of received texts, Donaldo has to guess the minimum possible number of girlfriends he has.
Input
The first line contains T (the number of test cases,
0 <= T <= 50
). Then T test cases follows.
Each test case starts with a line with
N
(number of texts in Donaldo's inbox,
0 <= N <= 20000
). The following N lines contain a time of the format
H:M:S
(
H
= hour,
M
= minute,
S
= second,
0 <= H <= 23
,
0 <= M <= 59
,
0 <= S <= 59
). The i-th time is the exact time when i-th text was received (
1 <= i <= N
). The last line contains
I
(
1 <= I <= 86400
).
Note that:
A specific time can occur more than once.
The texts are opened randomly, so the times don't have any particular (increasing / decreasing) order.
The duration between sending and receiving a text is negligible.
Intervals are inclusive. (e.g. If an interval of 5 seconds starts at 0:0:55, it will end at 0:0:59).
Output
For each testcase, output a line containing “
Case X: Y
”, where X is the case number and Y is the minimum possible number of Donaldo's girlfriends.
Example
Input:
2
3
8:39:17
17:17:17
21:59:59
86400
3
17:17:17
21:59:59
8:39:16
48042
Output:
Case 1: 3
Case 2: 2
Explanation
In the first test, all the texts are inside 86400 seconds duration. That means, each text is sent by a distinct girlfriend. So, number of Donaldo's girlfriends has to be greater or equal to 3.
In the second case, there are 2 possible time intervals containing 2 texts. One is containing the 1st and the 3rd time, and the other is containing the 1st and the 2nd time. So, any answer smaller than 2 is not possible. | 32,896 |
Queen Game (PK11E)
English
Vietnamese
Queen game is played in a chessboard of size R rows and C columns. Rows are numbered from 1 to R and columns are numbered from 1 to C. The topmost square is in row 1 and column 1. The game is a 2 player game. Initially there are N queens placed in various squares of the chessboard. In his turn, the player picks a queen and moves it either towards the top vertically, or towards the left horizontally or towards the top-left diagonally and the queen should always stay on the board. When the queen reaches square (1, 1) it is removed from the board. The player who gives the last move wins. Each square is big enough to accommodate infinite number of queens. The players give their moves by turns. You are given the size of the chessboard and the initial positions of the N queens. Assuming that both of the players play perfectly your task is to determine who will win this game.
Input
First line of the input contains T the number of test cases. Each test case starts with a line containing 3 integers R (1 ≤ R ≤ 25), C (1 ≤ C ≤ 10
15
) and N (1 ≤ N ≤ 1000). Each of the next N lines contains the positions of N queens. The position is denoted by two integers. The first integer is the row number and the second integer is the column numbers.
Output
For each test case output “YES” if the first player has a winning strategy and “NO” otherwise. Look at the output for sample input for details.
Example
Input:
3
5 5 1
2 3
5 5 2
4 4
4 4
5 5 3
1 2
2 1
2 2
Output:
NO
NO
YES | 32,897 |
Spelling Suggestion (PK11F)
A spelling suggestion is a part of spelling correction program that generates a set of plausible replacements for words that are likely to be misspelled. One way to measure the plausibility of these replacements is to compute their edit distance against a given misspelled word. The edit distance between two words is the total number of edit operations that have to be done in order to transform one word into the other. Normally these edit operations are insertion, deletion and substitution of a single character including transposition of 2 consecutive characters.
For example, for a word “wonder”, if the deletion is applied at the character 'o', this word will transform into “wnder”. And if the substitution with 'a' is applied at 'o', it will become “wander”. And if the transposition is applied at “er”, it will become “wondre”.
In this edit distance strategy, the degree of similarity between two words is up to their minimum edit distance. If the minimum edit distance between
word1
and
word2
is lower than the distance between
word1
and
word3
, then
word1
is more similar to
word2
than to
word3
. So the
word2
is a better spelling suggestion for
word1
, comparing with
word3
.
Suppose that you are an employee of a software company which needs to build up a prototype of spelling suggestion program. This prototype tends to be a part of word processing software. The requirement is that it has to use the edit distance strategy for their spelling suggestion. But the substitution operation has to be redefined to match the behavior of mistyping. The cost of substitution of a character with another character depends on the position of them on the keyboard layout. If they are close to each other, the cost is only half of the normal one. For this purpose, the substitution is categorized into near-substitution and far-substitution. Their costs are defined as 1 and 2 respectively. And the costs for insertion, deletion and transposition are 2. In addition, this program must run fast enough to pass the time limit that is set by your manager. By the way for this prototype, an English QWERTY keyboard layout is chosen to be used.
Goal
To generate optimum spelling suggestions for each input word, where each optimum spelling suggestion is a word in dictionary that has the least minimum edit distance from the given input word. The time limit for 5,000 misspelled words is less than or equal to 5 minutes.
Input
Input is a standard input which contains 3 parts of data. Each of these three parts ends with a blank line.
The first part is a set of near-substitution rules, where each rule is kept in one line. Each line has two fields. Each field is separated by a space. The total number of rules is less than or equal to 150.
The first field is a character where it can be near-substituted with other characters.
The second field is a sequence of characters which can be near-substituted for the character in the previous field. There is no space in this field.
The characters that may be contained in this part are characters that can be typed in using a generic English keyboard layout, which are alpha-numeric characters and some punctuations without space or tab.
They are listed as the following.
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+\|[{]};:'”,<.>/?
The second part is a sequence of words in dictionary, where each word is kept in one line. The total number of words is less than or equal to 150,000.
The characters in dictionary are alphabetical characters with an apostrophe punctuation: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’
The third part is a sequence of words that need to be checked for their spellings. Each of these words is also kept in one line. The total number of words is less than or equal to 5,000. The characters that may be contained in this part are the same as characters in the first part, which are alpha-numeric characters and some punctuation. (See the first part.)
Since each of these three parts end with a blank line, the third blank line is the termination of the input.
Output
For each word in the third part, write a line which contains 3 parts of information, separated with a colon.
The first part is the given input word.
The second part is the minimum edit distance between the input word and suggestion word(s).
The third part is an ascending sorted sequence of suggestion word(s), separated with a space. There is no space left after the last word.
Example
Line number
Sample Input
1
a AqQsSzZ
2
b BgGvVnN
3
p P0);:oO[{
4
r R4$fFeEtT
5
z ZaAxX
6
7
a
8
A
9
b
10
B
11
Z
12
angel
13
angle
14
anger
15
angry
16
ABC
17
18
x
19
s
20
z
21
xx
22
xxx
23
angre
24
angri
25
angrt
26
angel
27
ACB
28
BAC
29
CAB
30
Line number
Sample Output
1
x:2:A B Z a b
2
s:1:a
3
z:1:A Z a
4
xx:4:A B Z a b
5
xxx:6:A ABC B Z a b
6
angre:2:anger angle angry
7
angri:2:angry
8
angrt:2:anger angry
9
angel:0:angel
10
ACB:2:ABC
11
BAC:2:ABC
12
CAB:4:A ABC B
More Explanations
In this sample input, there are 5 near-substitution rules (line number 1-5), 10 words in dictionary (line number 7-16) and 12 words looking for their suggestions (line number 18-29).
In the sample output, there are 12 lines for each corresponding 12 words from the input.
For the 1
st
word, the minimum edit distance between x and its suggestions (A B Z a b) is 2. All of them are the (far) substitution costs.
For the 2
nd
word, the minimum edit distance between s and its suggestion (a) is 1, which is a near-substitution cost, guided by the 1
st
substitution rule.
For the 3
rd
word, the minimum edit distance between z and its suggestion (A Z a) are 1, which is a near-substitution cost, guided by the 1
st
or 5
th
substitution rule.
For the 4
th
word, the minimum edit distance is 4, which are summed from one far-substitution cost and one deletion cost.
For the 5
th
word, the minimum edit distance is 6. The costs between xxx and (A B Z a b) are from two deletion and one far-substitution costs.
The cost between xxx and ABC re from three far-substitution costs.
For the 6
th
word, the cost between angre and anger is from one transposition costs. The costs between angre and (angle angry) are from one far-substitution costs.
For the 7
th
word and 8
th
word, seem to be similar. But the cost of 7
th
word is from one far-substitution costs.
But the cost between angrt and anger is from 2 near-substitution costs (r substitutes with e and t substitutes with r) according to the near-substitution rule number 4.
For the 9
th
word, the word is exactly matched within dictionary. So the cost is 0.
For the 10
th
and 11
th
words, each cost is from one transposition costs.
For the 12
th
words, the cost between CAB and (A B) is from two deletion costs. The cost between CAB and (ABC) is from one deletion and one insertion costs.
Please be notify that it is not from 2 transpositions of CAB to ACB and then ACB to ABC. | 32,898 |
Paths in a Tree (PK11I)
English
Vietnamese
You are given a tree (a connected graph with no cycles), and the edges of the tree which are for some reason directed; your task is to add
minimum
number of special paths in the tree such that it's possible to go from any node to another. The rules for the special paths are noted below:
A special path consists of some continuous edges (from the tree) and nodes.
In a special path, the edges should be in opposite directions as they are in the tree.
A node or an edge can be visited at most once in a special path.
Multiple special paths may have common nodes or edges.
For example, in the picture below, a tree is drawn, the black arrows represent the edges and their directions, circles represent nodes. Then we need two special paths. One path is
2-1-0
(green arrow), another is
3-1
(blue arrow). Instead of the path
3-1
we can add
3-1-0
. You cannot add a path like
1-3
or
0-1-2
because of rule 2. You cannot add
0-2
or
2-3-0
because of rule 1.
Input
Input starts with an integer
T
(≤ 30), denoting the number of test cases.
Each case starts with a line containing an integer
N
(2 ≤
N
≤ 20000), where
N
denotes the number of nodes. The nodes are numbered from
0
to
N-1
. Each of the next
N-1
lines contains two integers
u v
(0 ≤
u
,
v
<
N
,
u
≠
v
) meaning that there is an edge from
u
to
v
.
Output
For each case, print the case number and the minimum number of special paths required such that it's possible to go from any node to another.
Example
Input:
2
4
0 1
1 2
1 3
5
0 1
1 2
1 3
0 4
Output:
Case 1: 2
Case 2: 3 | 32,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.