task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Manipulate Dwarfs (DWARFLOG)
In a small village beyond seven hills and seven seas, Snow White lives together with N dwarves who spend all their time eating and playing League of Legends. Snow White wants to put an end to this, so she has organized gym classes for them.
At the beginning of each class, the dwarves must stand in line, ordered by their height. For the purposes of this task, assume that the dwarves have heights 1, 2, ... N (each exactly once) and initially all are standing in sorted order with height from 1 to N. Now Snow White play on them by issuing commands of the form:
1 X Y -- dwarves with height X and Y in the line must switch places. She also checks their ordering by issuing queries of the form:
2 A B -- do dwarves with heights A, A+1, ... B (not necessarily in that order) occupy a contiguous subsequence of the current line? Help the doofus dwarves follow Snow White's instructions and respond to her queries.
Input
The first line of input contains the two positive integers N and M, the number of dwarves and the number of Snow White's requests, respectively (2 ≤ N ≤ 200 000, 2 ≤ M ≤ 200 000). Each of the following M lines contains a single Snow White's request, of the form "1 X Y" (1 ≤ X, Y ≤ N, X ≠ Y) or “2 A B” (1 ≤ A ≤ B ≤ N), as described in the problem statement.
Output
The output must contain one line for each request of type 2, containing the reply to the query, either “YES” or “NO”.
Example
Input:
4 5
2 2 3
2 2 4
1 1 3
2 3 4
1 4 3
Output:
YES
YES
NO | 33,900 |
Petya Brother and Repairment of Roads (PETYABRO)
Petya lives in a city named Mayapur. As in the morning, everybody likes to drink hot tea in bed. So the citizens of Mayapur need milk to produce tea. For this purpose, they want to be able to go to a milkman using the bi-directional roads. There are m roads in the city. Every year these roads become unfit for transportation, hence they have to be repaired each year.
Last year Petya repaired those roads. As Petya was short of money last year, he repaired them such that with minimum budget everyone could get milk from someone. Since then he received some complaints that some people had to walk for a long distance to get milk. So this year Petya want to repair the roads such that everyone can go to their nearest milkmen to get milk. So he has to select some roads to repair such that every citizen is connected to at least one milkman and that milkman is the nearest one for that citizen. For repairing each road he needs to pay the necessary cost. As he does not want to spend a lot of money in it, He wants to minimize the cost needed in this project. Note that a milkman does not need to go to some other milkman for milk as he can take milk from his own home. But Petya was a little bit bored to plan this time so he asked his brother to help him.
Now it is your job to help Petya's Brother in finding the minimum cost needed to repair the roads in the above given way. If it is not possible for a citizen to connect to any of the milkmen, output "impossible" (without quotes).
PS: Note that you should print the minimum cost needed such that everyone can go to their nearest milkman.
Input
First line contains two space separated numbers n and m: n is the number of citizens in Mayapur and m is the number of unrepaired roads.
Next line contains n space separated integers either 0 or 1 which indicates that citizen is milkman or not [1 means he is a milkman].
Then each of the next m lines contain three space separated integers u, v and c, denoting that there exists an unrepaired road between u and v such that the cost of repairing the road is c.
1 ≤ n ≤ 10
5
1 ≤ m ≤ min(n × (n - 1) / 2, 2 × 10
5
)
1 ≤ u, v ≤ n and u ≠ v
1 ≤ c ≤ 10
9
Output
Print the cost, or if not possible print "impossible".
Example
Input:
5 7
0 1 0 1 0
1 2 11
1 3 1
1 5 17
2 3 1
3 5 18
4 5 3
2 4 5
Output:
5
PS: for python users please make your submission using fastio or you can submit the solution into pypy. | 33,901 |
She was in Love with BST (LOVEBIRDS)
Devo! She has broken up with him again!
And after a series of break ups and patch ups, she is done with him!
Being a geek to keep herself distracted, she picks up her favourite topic of dynamic programming where she comes across this idiot problem which says:
Given a integer N, you have to tell the sum of number of structurally unique binary search trees built on different permutations of the set {x, x such that x belongs to [1, N] and x is an integer}.
A binary search tree is said to be built on a permutation iff the in-order traversal of that BST is same as the permutation.
A permutation is said to be distinct from another if there exists a position i such that the i'th element of the permutations is different.
Now, her inability to solve the problem is quite stressful to her! Help her in solving the problem!
Note: She observes that this number can be very large so output this number modulo 1908.
Moreover she tells you that there in-order traversal of a binary search tree is unique.
For binary search tree read Wikipedia's
binary search tree
.
Input
The first line of the input consists of T, the number of test cases.
The following T lines consists of a single integer N.
(N can be at max 1000, T can be at max 1000)
Output
You have to output T lines each consisting of the answer to the problem modulo 1908.
Example
Input:
2
1
2
Output:
1
2 | 33,902 |
PLAYING WITH BITS (BITPLAY)
The problem is very
simple
.
You
are given a even number
N
and an integer
K
and you have to find the greatest odd number
M
less than
N
such that the sum of digits in binary representation of
M
is at most
K
.
Input
For each test case, you are given an even number
N
and an integer
K
.
Output
For each test case, output the integer
M
if it exists, else print
-1
.
Constraints
1 ≤
T
≤ 10
4
2 ≤
N
≤ 10
9
0 ≤
K
≤ 30
Example
Input:
2
10 2
6 1
Output:
9
1
Explanation
First case when
N
= 10,
K
= 2
Binary representation of
10
is
1010
and binary representation of
9
is
1001
, hence greatest odd number less than
10
whose sum of digits in its binary representation is at most
2
is
9
. Hence
output
is
9
. | 33,903 |
1807 (SMILEY1807)
There is a SmileyLand of angels. The queen of all angels Smiley1807 loves the number 1807. She is so much obsessed with 1807 that she asked her programmer friend to write a program to find the length of the largest sub sequence having digits 1, 8, 0 and 7 in order. For example if given sequence is 1800777700088888000777 then one of the largest sub sequence satisfying the above condition is 1800000000777 (there is one more possibility of 1888888000777) and hence the length of largest sub sequence is 13.
Input
The input contains only one test case.
The test case consist of only one sequence which may be as long as 10
6
. There are only 1, 8, 0 or 7 present in the input sequence.
Output
Output contains only one line containing the length of the largest sub-sequence.
Example
Input:
1800777700088888000777
Output:
13
Explanation
1800000000777 is the largest sub-sequence | 33,904 |
Checking cubes. (BOKAM143SOU)
Given a integer N. Find number of possible ways to represent N as a sum of at most five cubes.
Input
First line contains N.
1<=N<=125000.
Output
Output the result
Example
Input:
64
Output:
2 | 33,905 |
Red Blue Line Segments (CS345A1)
There are n vertical line segments colored red and there are n horizontal line segments colored blue. We wish to find the number of red-blue pairs of intersecting segments.
These line segments are inside a unit square. Each blue segment is created by generating 3 random numbers (x
1
, x
2
, y) in the interval [0, 1]. These 3 numbers represent the segment joining (x
1
, y) and (x
2
, y). Red segments are generated similarly.
Input
First line contains the number of segments n (n ≤ 100000)
next n lines define the blue segments. Each line contains 3 floating point numbers (in [0, 1]) x
1
x
2
y representing the segment joining (x
1
, y) and (x
2
, y).
next n lines define the red segments. Each line contains 3 floating point numbers (in [0, 1]) y
1
y
2
x representing the segment joining (x, y
1
) and (x, y
2
).
Output
Print a single line containing the number of intersections.
Note: Touching line segments also count as intersecting. For example - blue segment joining (0.1, 0.2) and (0.3, 0.2) intersects with red segment joining (0.3, 0.4) and (0.3, 0.2).
Example
Input:
3
0.36295 0.557494 0.184032
0.0479258 0.214097 0.508344
0.234284 0.969098 0.739363
0.499323 0.739797 0.138495
0.829265 0.22551 0.290582
0.791082 0.069214 0.450979
Output:
4 | 33,906 |
Subsequences with modulo (KNMD)
You are given sequence
A
1
, A
2
, ... A
n
and integer
k
. For each integer
i
(0 ≤ i < k)
find such
nonempty
subsequence of
A
so that sum of numbers in this subsequence is maximal possible and remainder of integer division of this sum by
k
is equal to
i
.
Input
In first line numbers
n
and
k (1 ≤ n ≤ 10
6
, 1 ≤ k ≤ 200)
.
In second line:
n
numbers representing sequence
A (1 ≤ A
i
≤ 10
9
)
.
Output
Print
k
numbers in one line.
i
'th number represent sum of numbers in subsequence for number
i - 1
. If there is no such subsequence print -1.
Example
Input:
6 5
2 8 10 44 15 32
Output:
65 111 77 103 109 | 33,907 |
Nth Prime (NTHPRIME)
There is no tedious description for this problem. You are just required to calculate and output the
Nth
prime number.
Input
The input consists of a single line containing an integer
N,
N
≤
10^9
.
Output
For each input file, output the
Nth
prime number.
Example
Input:
4
Output:
7
Note
The source limit is enabled to
4000B
in order to restrict and discourage sending solutions with pre-computed tables. | 33,908 |
Robot (ROOBOT)
There is a robot on the 2D plane. Robot initially standing on the position (0, 0). Robot can make a 4 different moves:
Up (from (x, y) to (x, y + 1)) with probability
U
.
Right (from (x, y) to (x + 1, y)) with probability
R
.
Down (from (x, y) to (x, y - 1)) with probability
D
.
Left (from (x, y) to (x - 1, y)) with probability
L
.
After moving
N
times Robot gets points.
Let x
1
be the smallest coordinate in X-axis, that Robot reached in some moment.
Let x
2
be the largest coordinate in X-axis, that Robot reached in some moment.
Let y
1
be the smallest coordinate in Y-axis, that Robot reached in some moment.
Let y
2
be the largest coordinate in Y-axis, that Robot reached in some moment.
Points achieved by Robot equals to x
2
- x
1
+ y
2
- y
1
.
Given
N, U, R, D, L
. Calculate
expected value
of points that Robot achieved after
N
moves.
Input
First line: One interger
N (1 ≤ N ≤ 200)
.
Second line: Four real numbers
U, R, D, L (U + R + D + L = 1, 0 ≤ U, R, D, L
≤ 1
) with maximum of 6 numbers after dot.
Output
One number: expected value of points achieved by Robot. The answer will be considered correct if its relative or absolute error does not exceed 10
-6
.
Example 1
Input:
2
0.100000 0.200000 0.300000 0.400000
Output:
1.780000
Example 2
Input:
3
0.25 0.25 0.25 0.25
Output:
2.375000 | 33,909 |
Fibonacci Polynomial (FIBPOL)
Let
F(n)
be the
n
th
member of the Fibonacci sequence
:
F(0) = 0,
F(1) = 1,
F(n) = F(n-1)+F(n-2) (n > 1)
Consider the following Fibonacci polynomial:
A(x) = x F(1) + x
2
F(2) + x
3
F(3) + ... + x
n
F(n) + ... = sigma(n = 0 to infinity) x
n
F(n)
Amazingly,
A(1/2) = 1/2 + 1/2
2
+ 2/2
3
+ 3/2
4
+ .... + F(n)/2
n
+ ... = 2
In this problem, we only considering the non-negative-integer value of A(x). Here are some examples of A(x) for specific x.
x
A(x)
0
0
sqrt(2)-1
1
1/2
2
[sqrt(13)-2]/3
3
[sqrt(89)-5]/8
4
Find out if x is rational with the given value of A(x)
Input
The first line contains T, the number of test cases. The next T lines contains the value of A(x).
0 <= Ax <= 10^17
1 <= T <= 100000
Output
1 if the given Ax yields a rational x, 0 otherwise
Example
Input:
5
0
1
2
3
4
Output:
1
0
1
0
0 | 33,910 |
Largest Odd Divisor (DOL)
Given a non-negative integers
N
. You have to find the largest odd divisor of
N
.
Input
Input starts with an integer
T (1<=T<=5000)
denoting the number of test cases. Each test case contains an integer
N (1<=N<=10
12
)
.
Output
For each test case print the case number and the largest odd divisor of
N
.
Sample Input
Output for Sample Input
2
2
10
Case 1: 1
Case 2: 5
Problem Setter: Md Abdul Alim, Dept. of Computer Science, Bangladesh University of Business & Technology | 33,911 |
Truncky Numbers (ADST01)
Asutosh is very passionate about numbers. he has found a new type of numbers and calls them 'truncky numbers'.
He has challenged his friend Shantanu to find the sum of first n truncky numbers. As shantanu is weak at programming, help him to complete his challenge.
A truncky number is defined as:
sum of digits in the number is of the form (5*k + 1) where k = number of digits.
absolute difference between any two digits in the number is either 0 or 1.
digits are in the non decreasing order.
Input
the first line contains T (number of test cases). Each test contains only one integer n.
Output
Print in single line sum of first n truncky numbers modulo 10^9 + 7.
Each output in new line.
Constraints
T <= 30
N <= 10^17
Example
Input:
1
2
Output:
62 | 33,912 |
Star (STARSBC)
Fernando won a compass for his birthday, and now his favorite hobby is drawing stars: first, he marks
N
points on a circumference, dividing it into
N
equal arcs; then, he connects each point to the
k-th
next point, until returning to the first point.
Depending on the value of
k
, Fernando may or may not reach all points marked on the circumference; when that happens, the star is called complete. For example, when
N
= 8, the possible stars are shown in the figure below. Stars (a) and (c) are complete, while stars (b) and (d) are not.
Depending on the value of
N
, it may be possible to draw many different stars; Fernando asked you to write a program that, given
N
, determines the number of complete stars he can draw.
Input
The input contains several test cases. Each test case contains a single line, containing a single integer
N
(3 ≤
N
< 2
31
), indicating the number of arcs in which the circumference was divided.
Output
For each test case, your program must print a single line containing a single integer, indicating the number of complete stars that can be drawn.
Example
Input:
3
4
5
18
36
360
2147483647
Output:
1
1
2
3
6
48
1073741823 | 33,913 |
Compare Substring (CMPSSTR)
* This problem is of authorship and property of TopCoder (www.topcoder.com/tc) and adapted by Alessandro B. for authorized use in URI OJ.
* Unauthorized reproduction of this problem statement without the prior written consent of TopCoder, Inc. is strictly prohibited.
Find the longest common substring between the two informed Strings. The substring can be any part of the String, including the entire String. If there is no common substring, return 0. The search is
case sensitive
('x' ≠ 'X').
Input
The input contains several test cases. Each test case is composed by two lines that contains a string each. Both input Strings will contain between 1 and 50, inclusive, letters (a-z, A-Z), and/or spaces.
Output
The length of the longest common substring between the two Strings.
Example
Input:
abcdef
cdofhij
TWO
FOUR
abracadabra
open
Hey This java is hot
Java is a new paradigm
Output:
2
1
0
7 | 33,914 |
Elegant Permuted Sum (ELPESUM)
Special Thanks: Jane Alam Jan
*At moment in University of Texas at San Antonio - USA
You will be given
n
integers
A
1
A
2
A
3
...A
n
. Find a permutation of these
n
integers so that summation of the absolute differences between adjacent elements is maximized.
Suppose
n = 4
and the given integers are
4 2 1 5
. The permutation
2 5 1 4
yields the maximum summation. For this permutation
sum = abs(2-5) + abs(5-1) + abs(1-4) = 3+4+3 = 10
.
Of all the
24
permutations, you won’t get any summation whose value exceeds
10
. We will call this value,
10
, the
elegant permuted sum
.
Input
The first line of input is an integer
T
(
T
< 100) that represents the number of test cases. Each case consists of a line that starts with
n
(1 <
n
< 51) followed by n non-negative integers separated by a single space. None of the elements of the given permutation will exceed 1000.
Output
For each case, output the case number followed by the
elegant permuted summation
.
Example
Input:
3
4 4 2 1 5
4 1 1 1 1
2 10 1
Output:
Case 1: 10
Case 2: 0
Case 3: 9 | 33,915 |
Kaos (KAOS)
Little Lovro likes to play games with words. During the last few weeks he realized that some words don't like each other.
The words A and B
don't like
each other if
the word A is lexicographically before the word B
, but
the word B' is lexicographically before the word A'
, where X' stands for the word X reversed (if X = “kamen”, then X' = “nemak”). For example, the words “lova” and “novac” like each other, but the words “aron” and “sunce” don't like each other.
Given some set of the words, we define
the degree of chaos
of the set as
the number of pairs
of different words that
don't
like each other.
Write a program that, given a set of words, finds the chaos degree for the set.
Input
The first line of input contains an integer
N
, 2 ≤
N
≤ 100 000.
Each of the following
N
lines contains one word – a sequence of at most 10 lowercase letters of the English alphabet ('a' – 'z'). There will be no two identical words in the set.
Output
The first and only line of output should contain a single integer – the chaos degree of the given set of words.
Note: use 64-bit signed integer type (int64 in Pascal, long long in C/C++)
Examples
Input:
2
lopta
kugla
Output:
0
Input:
4
lova
novac
aron
sunce
Output:
3
Input:
14
branimir
vladimir
tom
kruz
bred
pit
zemlja
nije
ravna
ploca
ko
je
zapalio
zito
Output:
48 | 33,916 |
Gyanbabas Admission Test (SUBPAL)
Gyanbaba is the wisest saint of the universe. People from all over the world come to him to seek gyan (knowledge). But he does not offer his wisdom to everyone. He choses the right person to give wisdom after taking a test, his murids (apprentices) call this Gyanbaba's Admission Test. For the admission test Gyanbaba writes down a string containing lowercase English letters only and asks the applicants to find the substring of maximum length, the characters of which can be permuted to create a palindrome. Can you pass his test?
Input
Input starts with an integer
T (≤ 30)
, denoting the number of test cases.
Each case has a string
S
, the string Gyanbaba chose. You can assume
1 ≤ length(S) ≤ 100000
.
Output
For each case print one line containing the case number starting with 1 and the length of the substring, which satisfies Gyanbaba's query.
Example
Input:
2
abcfebcbbcbd
fesdddssefseefs
Output:
Case 1: 7
Case 2: 13 | 33,917 |
Acceptable numbers (KBASEEN)
Sitting in front of computer has made Byteasar's eye sight very bad. He has to wear glasses to fix it. But Byteasar doesn't like it. So everything associated with glasses is disliked by him.
Byteasar has been working with different numeral systems. When listing numbers, he knows exactly which of them aren't liked by him. Of course these numbers have two zeros next to each other. Now he is wondering: how many
n
-digits numbers in
k
-base numeral system he is able to accept. There could be many of them so print the result modulo
m
.
Input
First there is a
t
(0 <
t
< 1001), number of test cases.
Each test contains three number:
n
(0 <
n
< 10
18
),
k
(1 <
k
< 10
18
) and
m
(1 <
m
< 10
18
).
n
is a length of the number,
k
- digits quantity in given numeral system.
Output
For each test print answer divided modulo
m
.
Example
Input:
2
4 2 100
3 10 10000
Output:
5
891 | 33,918 |
Ohani And The Game (OHANIGAME)
One day Ohani and her friend was playing a game. The rules of the game is given below:
Ohani Starts the game. Then the two player take turns.
At the starting of the game, Ohani and her friend together choose a number N.
They take the absolute value of N, N = |N| or, N = abs(N).
In one turn: a player chooses a divisor X of N where 1 < X ≤ N. Then he/she divides N by X. Then next player continues to do step 4 until N is not equal to 1.
The game ends when N becomes 1.
The player who can’t make his/her next move, looses the game. Both the player plays optimally.
Ohani and her friend was playing the game for a long time. So, they got bored. Then suddenly one interesting idea came to Ohani’s mind. She wants to choose maximum number of ways to get 1 from N such that no two way has a common number except 1 and N?
For explanation:
Suppose N = 20.
Two possible way to get 1 is: 20 → 10 → 5 → 1 and 20 → 5 → 1, both the way has number 5 in common.
But: 20 → 10 → 1 and 20 → 4 → 2 → 1 has no number common without 20 and 1.
So, now Ohani wants to know the number of ways such that no two way has common number except 1 and N. But Ohani is very weak in coding. So, she wants you to help.
Input
The first line of the input contains the number of test cases T (≤ 100000).
Each of the next T lines contains a number N (|N| ≤ 1000000).
Output
For each test case, output the desired answer. If it is impossible to reach 1, just print “Impossible”.
Example
Input:
3
1
2
3
Output:
0
1
1 | 33,919 |
Defense of a kingdom 2 (DEFKIN2)
This is an extension to the problem DEFKIN http://www.spoj.com/problems/DEFKIN/ and solve it first before doing this.
Theodore implements a new strategy game “Defense of a Kingdom”. On each level a player defends the Kingdom that is represented by a rectangular grid of cells. The player builds crossbow towers in some cells of the grid. The tower defends all the cells in the same row and the same column. No two towers share a row or a column.
Now the king inputs width(w),height(h),number of towers(n). Here n <= min(w, h).
There there can be many ways to place the towers in the grid.
Lets define a function penalty(N
i
) for the ith combination of tower placements, which is number of cells in the largest undefended rectangle. For example, one of the combinations of placing a tower is shown in the picture and has a penalty=12.
Suppose there are in total k combinations. Then there are penalty(N
1
), penalty(N
2
), penalty(N
3
) ... penalty(N
k
).
The task of the user is to find the minimum of these penalties.
Input
The first line of the input file contains the number of test cases.
Each test case consists of a line with three integer numbers: w — width of the grid, h — height of the grid and n — number of crossbow towers (1 ≤ w, h ≤ 40 000; 0 ≤ n ≤ min(w, h)).
Output
For each test case, output a single integer number- the minimum penalty. Output answer for each test case in a new line.
Example
Input:
1
15 8 3
Output:
6 | 33,920 |
ChickenLove (FOODIES)
A new grand chicken stall is about to open in Chennai. Buddy and Pre being close friends joined hands and planned to go for it. People have to serve themselves here in this stall.
There are N-counters available and each counter has a specified number of chicken nuggets.
The cost of each nugget being bought at any counter is same as the number of nuggets that are still remaining at the counter at that point of time (inclusive of the nugget being bought).
Pre wants to have M nuggets. As usual Buddy accepts to sponsor Pre with all his pocket money. He is so innocent that he obeys each and every order of Pre with no second thought. Pre being cunning wants Buddy to spend her too much money. So she directs buddy to buy nuggets at the counters which she says, so that he spends maximum money for her.
Of course you can't help Buddy :( But try to find him how much he would spend for Pre, if he obeys her like an IDIOT.
Input
The first line of the input contains the number of test cases, T. T test cases follow:
The first line of each test case contains an integer N, denoting the number of counters.
The next line consists of N integers: A1, A2, ... An denoting the number of nuggets available at each counter.
The next line consists of a single integer M, number of nuggets Pre wishes to have.
Output
For each test case output a single integer in a single line denoting the money that buddy would spend.
Constraints
1 <= T <= 10
1 <= N <= 100000
1 <= A1, A2 ... An <= 100000
1 <= M <= A1 + A2 + A3 + ... + An
Example
Input:
1
3
3 5 4
3
Output:
13
Explanation
Pre would ask buddy to get two nuggets from the second counter (5 + 4 = 9), and then one from the third counter (9 + 4 = 13) | 33,921 |
Save Area 11 (SVAREA11)
In the year 2010 of the Imperial Calendar, the Holy Britannian Empire invaded Japan and overpowered the defending forces. Japan became a dominion of the Empire. The country was stripped off her freedom, her rights and her name. The defeated and once proud nation was given a mere number as a name - Area 11.
After many years, Lelouch vi Britannia, the leader of the Black Knights, is making plans for some important battles against the Holy Britannian Empire army in his quest to free Area 11. He is assigning soldiers of the Black Knights to various strategically advantageous positions on the battlefields.
Lelouch assigns a soldier to a position from T
1
second to T
2
second. The soldier leaves to fight at the beginning of T
1
second and returns at the end of T
2
second. During this time, this soldier is unavailable for any other assignments. After returning, he is available for future assignments. A complete plan includes several of these assignments.
The Black Knights does not have unlimited number of soldiers. Lelouch has made plans for several battles and now he is trying to distribute his soldiers to carry out these plans. He takes a plan and allocates
N
soldiers for it. Then he asks you to check if the plan can be carried out successfully with N soldiers.
Help Lelouch make the plans. The fate of Area 11 depends on you!
Input
Input begins with an integer
P (1 ≤ P ≤ 105)
, indicating the number of plans. Then follows the P plans. Each plan begins with two integers
N (0 ≤ N ≤ 10
9
)
and
A (0 ≤ A
≤
10
4
)
,
indicating the number of soldiers allocated for that plan and the number of assignments that plan has respectively. The next A lines each contains two integers
S
and
E (1 ≤ S ≤ E ≤ 10
4
)
, indicating the starting and the ending time of an assignment.
Output
For each plan, print a single line in the format
Plan X: Y
, where X is the plan number and Y is either
Yes
or
No
, indicating whether the plan can be completed successfully or not.
Example
Input:
2
3 3
1 3
1 4
1 2
2 3
1 3
1 4
1 2
Output:
Plan 1: Yes
Plan 2: No
Note:
Dataset is huge. Use faster I/O method. | 33,922 |
Candies (ICANDIES)
Sava is a student of class X. She has two little sisters Sara and Sami. Sara is only 3 years old and Sami is a girl of 5 years. At her birthday Sava bought N candies and wants to divide them between her two sisters Sara and Sami. But as Sara is 3 years old she wants such amount of candies that is perfectly divisible by 3. Sami also wants the amount of her candies to be perfectly divisible by 5 and only this way both of them are happy otherwise they become unhappy.
So, Sava wants to make both of them happy. Now for some value of N Sava can divide the candies in various ratio that will make her sisters happy. But as Sara is the youngest one she wants to give the maximum number of candies she can. As Sava is not good enough in math, she wants your help.
Input
Input starts with an integer T (1 ≤ T ≤ 50), denoting the number of test cases. Each of the test cases consists an integer N (1 ≤ N ≤ 10
6
), the number of candies Sava bought.
Output
For each case print "Case X: " where X (1 ≤ X ≤ T) is the case number. And then, if it is possible to divide the candies making both of them happy print the maximum number of candies you can give to Sara. And if it is not possible to make both of them happy then print '-1' (without the quotes).
Example
Input:
3
8
9
20
Output:
Case 1: 3
Case 2: -1
Case 3: 15 | 33,923 |
Eefun Guessing Words (NPC2015A)
Eefun is currently learning to read. His way of learning is unique, by trying to make every possible substring from a given string. However, when the string becomes longer, he can no longer remember all the substring. His friends want to test Eefun's skill by asking questions, given a string S, is there any substring that begins with letter X and ends with letter Y? According to Eefun, each substring contains at least 2 letters. As the given string S is pretty big, Eefun need your help to answer his friend's questions
Input
First line of input contain a single string S which was given by his friends.
Second line contain a number N, the number of questions that Eefun's friends ask.
Next N lines each consists of 2 characters, X and Y
Output
For each questions, output a single string "YA" if the substring exists, or "TIDAK" otherwise
(YA means yes and TIDAK means no in Indonesian)
Example
Input:
HALO
4
H O
L O
A O
O L
Output:
YA
YA
YA
TIDAK
Constraints:
'A' ≤ X,Y ≤ 'Z'
1 ≤ |S| ≤ 1.000.000
1 ≤ N ≤ 1.000.000 | 33,924 |
Eefun the Accountant (NPC2015B)
Eefun is an accountant. As an accountant, he loves to work with spreadsheet. In spreadsheet, a data must be saved into a single cell which has row and column. Spreadsheet has an interesting feature. It can move the cursor from a cell to another cell by clicking a button based on this rules :
If current cell has data and its right neighbour also contain data
, then clicking the right button will make the cursor move to the first cell to the right of the current cell whose right neighbour doesn't contain data. If there is no such cell, then the cursor will move to the rightmost cell in the current row.
Else,
then clicking the right button will make the cursor to move to the first cell in the right of current cell which has data. If there is no such cell, then the cursor will move to the rightmost cell in the current row.
Same rules apply when clicking the left, up, and down button.
Eefun realizes this feature which makes him curious. He currently has a lot of data in his spreadsheet. He wants to edit a data on cell (R, C), but first he must move his cursor to the desired cell. Currently his cursor is at cell (1,1), the top-leftmost cell in the spreadsheet. Eefun wants to know the minimal number of button clicked to reach the cell.
Input
First line of input consists of 2 integers, N and M, the number of rows and number of columns
Second line consists of a number X, the number of data that Eefun currently has.
Next X lines each consists of 2 integers, A and B which denotes the position of the data
Line (X+3) contains a number Q, the number of query.
Next Q lines each consists of 2 integers, R and C, the position of cells that Eefun wants to edit
Output
For each query, output a single integer, the minimum number of buttons that Eefun should click to reach cell (R,C). If the cell cannot be reached, then output a string "Eefun gagal mengedit data"
"Eefun gagal mengedit data" means "Eefun fails to edit his data"
Note that each query is independent, so Eefun's initial cursor will be at (1,1) for each query
Example
Input:
3 3
8
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
2
3 2
1 3
Output:
Eefun gagal mengedit data
1
Note : You can try this in Microsoft Excel using ctrl + arrow button
Constraints:
1 ≤ X ≤ min(100.000 , N*M)
1 ≤ N,M ≤ 10.000
1 ≤ Q ≤ 100.000 | 33,925 |
Eefun Plays Doto (NPC2015C)
Doto is a famous game. In that game, each player controls N heroes where each heroes has an infinite number of skills. These skills can be used to empower other heroes. Eefun is currently playing with his N heroes, numbered from 1 to N.
The main objective of this game is to defeat the enemies with these heroes. However, Eefun always lose the game, so now Eefun only try to make his heroes powerful.
Based on Eefun's logic, there are M requirements to make all of his heroes powerful. Each requirement needs a hero A and a hero B. Hero A must use his/her skill to hero B to make B more powerful. Moreover, if hero B and C needs skill from hero A, hero A can use his/her skill to hero B. Then, hero B skills will be empowered with skills from hero A. Therefore, he can use his skill to hero C. In this scenario, the number of skills activated is 2, where A doesn't get any skills, B get skill from hero A, and C get skill from both hero A and B.
The skill is continuous, so if A give his skill to B, B give his skill to C, and C give his skill to A, then every hero get every other heroes skills
Now Eefun is curious, how many skills must be activated to complete all his requirements
Input
First line consists of 2 integers, N and M which denotes number of heroes and requirements.
Next M skills each contains 2 integers, A and B, which means hero B will be powerful if he get skills from hero A.
Output
Output an integer, the minimum number of skills which must be activated to complete all the requirements
Example
Input 1:
3 4
1 2
2 3
3 1
2 1
Output 1:
3
Input 2:
5 5
1 5
3 4
4 3
2 5
1 3
Output 2:
5
Explanation
For the first case, hero 1 can give his skill to hero 2, hero 2 can give his skill to hero 3, and hero 3 can give his skill to hero 1.
For the second case, one of the configuration is like in the picture below :
Constraints:
A ≠ B
1 ≤ A,B ≤ N
1 ≤ N ≤ 100.000
1 ≤ M ≤ 100.000 | 33,926 |
Eefun is not so Fun (NPC2015D)
Eefun is a young man who lives at Schematics village. His village will be visited by a school named Enpeesee. Eefun want to prepare a game for the students. After thinking for several days, he came up with a game called "Funny Eefun is fun".
Enpeesee's students have finally arrived. However, none of the students want to play with Eefun. Eefun gets disappointed.
Seeing tears on Eefun's face, one of the student, Andee, decide to play with Eefun. Eefun happily explains his game to Andee. Eefun currently has a number N. Then, Andee can think about numbers which sum is equal to N. However, the product of Andee's number should be maximum. Andee tried this game several times, but he never answered it right. Therefore, Andee gets frustrated and think that the game's title should be "Eefun is not so Fun". As Andee's best friends, help him to beat this game.
Input
Input contains a number N
Output
Output a number, the maximum product of Andee's number. As the number can be pretty large, output it with modulo 1000000007 (10
9
+7)
Example
Input 1:
2
Output 1:
2
Input 2:
5
Output 2:
6
Constraints:
1 ≤ N ≤ 10
18 | 33,927 |
Eefun Plays LOL (NPC2015E)
Palkia is playing a popular game called "Lol of Legend". In that game, each player controls 1 champion where each champion has a finite number of skills. These skills can be used to empower other champions.
The main objective of this game is to defeat the enemies with these champions. However, one of Palkia's team member, Eefun, is unable to do that. Eefun only try to make his champions powerful.
Palkia angrily smashes the world where Eefun live with his superpower. Eefun is now stranded in NLC world and he meets Elsee. It turns out that the people of NLC world like playing with riddles and logic puzzles. Long story short, Eefun entered a logic contest and reach the finals. In the finals, Eefun has to solve this problem:
Elsee's father has a quite large coconut farm. The coconuts in this farm have different durabilities. Durability is determined by how high the coconut can be dropped without breaking. If a coconut has 50 durability, then it will break if dropped from 51 height. But, the coconut will not break or damaged if dropped from 50 height. Each coconut has a minimum of 0 and maximum of 2014 durability. Elsee is given two coconuts with the same durability by his father, however Elsee doesn't know their durabilities. Elsee wants to test the durability by dropping them from the window of a building. Worst case scenario, what is the minimum number of times Elsee need to drop the coconuts to know their durabilities? The building Elsee in has a height of 2014.
Eefun can't answer the question so he is eliminated. After the contest, Eefun got the solution from Elsee, which is 63. Eefun is determined to win the logic contest one day.
Palkia is feeling bad after what he's done, then he find another world that is similar to the previous world he destroyed, and he returned every inhabitant from the previous world to that new world. Eefun is sad because he can no longer enter the logic contest in NLC world. Eefun does not want his friendship with Elsee goes to waste so he created programming problem based on the problem that stumped him. Eefun then submits his problem to a programming contest and that problem is used in the contest. Here is the prolem:
Elsee's father has a quite large coconut farm. The coconuts in this farm have different durabilities. Durability is determined by how high the coconut can be dropped without breaking. If a coconut has 50 durability, then it will break if dropped from 51 height. But, the coconut will not break or damaged if dropped from 50 height. Each coconut has a minimum of 0 and maximum of
N
durability. Elsee is given
K
coconuts with the same durability by his father, however Elsee doesn't know their durabilities. Elsee wants to test the durability by dropping them from the window of a building. Worst case scenario, what is the minimum number of times Elsee need to drop the coconuts to know their durabilities? The building Elsee in has a height of
N
.
Input
First line of input contains a number T, the number of test cases. Next T lines each contains N and K, the maximum durability and number of coconuts.
Output
For each test case, output the minimum number of drop test that Elsee must do to find out the coconuts durability.
Example
Input:
3
100 2
2014 2
100000 1
Output:
14
63
100000
For all subtask
1 ≤ T ≤ 100000
Subtask 1:(10 points)
1 ≤ N ≤ 10
18
1 ≤ K ≤ 2
Randomly generated
Subtask 2:(30 points)
1 ≤ N ≤ 1000
1 ≤ K ≤ 1000
Subtask 3:(60 points)
1 ≤ N ≤ 10
18
1 ≤ K ≤ 10
18
If you encounter a bug with the custom judge, please let me know in the comment. | 33,928 |
Eefun and Doors (NPC2015F)
Eefun is a nomad who like to explore dungeons. On each dungeons, there's a valuable treasure waiting for him. However, Eefun should pass some obstacles to get the treasure.
In the dungeon, there are N doors which moves every second. These doors have width equal one and the dungeon has M width. When Eefun enters the dungeon (pass the first door), the timer start and the doors will start moving. The door will move to the right initially. When a door reach the end of the dungeons (at position M), then the door will change direction to left until reaching the leftmost position again (position 1). Eefun knows the initial position of all doors.
To pass a door, Eefun need to have same position with the door and he needs a second to pass a door. If next door has different position with Eefun, he can stay at the current position or move a position to the left or right.
After trying many dungeons, Eefun gets dizzy because he sees moving door everywhere. Therefore, he wants to know the minimum number of seconds to get the treasure. Eefun can obtain the treasure after he pass all the doors.
Input
First line contains 2 numbers, N and M.
Second line contains N numbers, the initial position of each doors.
Output
Output a single number, the minimum time Eefun needs to obtain the treasure.
Example
Input 1:
3 5
1 4 3
Output 1:
5
Input 2:
5 5
1 1 1 1 1
Output 2:
18
Explanation
For the first testcase, the initial doors are like picture below:
|P****|
|-----|
|***P*|
|-----|
|**P**|
First, Eefun will enter the dungeon at time = 1 and the doors will start moving
|*P***|
|E----|
|****P|
|-----|
|***P*|
Then, Eefun will move to the right 2 times
|***P*|
|--E--|
|**P**|
|-----|
|***P*|
Then, Eefun will pass the second door which take one second.
|****P|
|-----|
|*P***|
|--E--|
|**P**|
As Eefun already has same position with the last door, he can continue to the last door and take another second. His minimum time to pass all the doors are 1+2+1+1 = 5 seconds.
Constraints:
1 ≤ Position of each door ≤ M
1 ≤ N ≤ 1.000.000
1 ≤ M ≤ 10.000 | 33,929 |
Hexagram (HEXGRAM)
A Hexagram is a 6-pointed star, sometimes called the Star of David. Given these numbers:
3 17 15 18 11 22 12 23 21 7 9 13
There are four unique ways of assigning the numbers to vertices of the hexagram such that all of the sets of four numbers along the lines have the same sum (57 in this case). All other ways may be obtained from these by rotation and/or reflection.
Given 12 distinct numbers, in how many ways, disregarding rotations and reflections, can you assign the numbers to the vertices such that the sum of the numbers along each of 6 straight lines passing through 4 vertices is the same?
Input
There will be several test cases in the input. Each test case will consist of twelve unique positive integers on a single line, with single spaces separating them. All of the numbers will be less than 1,000,000. The input will end with a line with twelve 0s.
Output
For each test case, output the number of ways the numbers can be assigned to vertices such that the sum along each line of the hexagram is the same. Put each answer on its own line. Output no extra spaces, and do not separate answers with blank lines.
Example
Input:
3 17 15 18 11 22 12 23 21 7 9 13
1 2 3 4 5 6 7 8 9 10 11 13
0 0 0 0 0 0 0 0 0 0 0 0
Output:
4
0 | 33,930 |
Meetings (MEETINGS)
At last you got lucky. You started working in a large reputable company. Someone appreciate your outstanding abilities and now you have an opportunity to show off. You can't wait for your first task.
You're following the manager who is leading you to the hallway full of doors. You got a piece of paper and all you heard from your new supervisor before he disappeared in one of the rooms: "Here's a list of scheduled meetings for the next week. Arrange them so that as many of them will take place."
Can you do that?
Input
At the begining there is
d
(0 <
d
≤ 1000) denoting the number of days to develop. Every day is defined as follows: first the number of available rooms
r
(0 <
r
≤ 10
5
) and scheduled meetings
m
(0 <
m
< 10
6
). Then
m
lines describing the meetings. Single meeting consists of four values:
bh
:
bm
,
eh
:
em
(0 ≤
bh
,
eh
≤ 23, 0 ≤
bm
,
em
≤ 59) which are time (in format: hours:minutes) of the begining and ending. No meeting begins and ends at the same time. The start time is always earlier than the end. Meetings take place within one day (no meetings begin one day and finish the next).
Size of the input files does not exceed 9M.
Output
For each day you have to specify the maximum number of meetings that can take place and assign meetings to rooms. In the next lines list meetings which will take place in each rooms.
Meetings are numbered in order they appear on the entry. Meetings are numbered from 1 to
m
.
Meetings can't overlap but could begin at the end of the previous one.
If meetings can be allocated on the several ways write any of them (meetings assigned to the room can be given in any order). There is a custom judge to check correctness of Your output.
Rooms are not numbered. If you can use 7 from 10 rooms just write 7 lines.
Separate solution for each day by empty line (even the last one).
Example:
Input:
2
2 3
11:20 12:00
11:30 11:40
11:40 11:55
3 6
17:15 18:30
17:20 19:00
17:15 18:00
16:55 17:55
17:10 18:10
17:00 18:00
Output:
3
1
2 3
3
1
2
3 | 33,931 |
New Lottery Game (LOTGAME)
The Lottery is changing! The Lottery used to have a machine to generate a random winning number. But due to cheating problems, the Lottery has decided to add another machine. The new winning number will be the result of the bitwise-AND operation between the two random numbers generated by the two machines.
To find the bitwise-AND of X and Y, write them both in binary; then a bit in the result in binary has a 1 if the corresponding bits of X and Y were both 1, and a 0 otherwise. In most programming languages, the bitwise-AND of X and Y is written X&Y.
For example:
The old machine generates the number 7 = 0111.
The new machine generates the number 11 = 1011.
The winning number will be (7 AND 11) = (0111 AND 1011) = 0011 = 3.
With this measure, the Lottery expects to reduce the cases of fraudulent claims, but unfortunately an employee from the Lottery company has leaked the following information: the old machine will always generate a non-negative integer less than A and the new one will always generate a non-negative integer less than B.
Catalina wants to win this lottery and to give it a try she decided to buy all non-negative integers less than K.
Given A, B and K, Catalina would like to know in how many different ways the machines can generate a pair of numbers that will make her a winner.
Could you help her?
Input
The first line of the input gives the number of test cases, T. T lines follow, each line with three numbers A B K.
1 ≤ A ≤ 10^9.
1 ≤ B ≤ 10^9.
1 ≤ K ≤ 10^9.
Output
For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is the number of possible pairs that the machines can generate to make Catalina a winner.
Example
Input:
5
3 4 2
4 5 2
7 8 5
45 56 35
103 143 88
Output:
Case #1: 10
Case #2: 16
Case #3: 52
Case #4: 2411
Case #5: 14377 | 33,932 |
Shuffles (SHUFFLES)
The most common technique for shuffling a deck of cards is called the Riffle or Dovetail shuffle. The deck is split into two stacks, which are then interleaved with each other. The deck can be split anywhere, and the two stacks can be interleaved in any way.
For example, consider a deck with 10 unique cards:
1 2 3 4 5 6 7 8 9 10
Split them somewhere:
1 2 3 4 5 6 7 8 9 10
And interleave them in some way:
1 2 7 3 8 9 4 5 10 6
Do it again. Split them somewhere:
1 2 7 3 8 9 4 5 10 6
And interleave them in some way:
3 8 1 9 4 5 2 7 10 6
This is one possible ordering after 2 shuffles. Suppose there are
n
unique cards, and that they start out perfectly ordered: 1, 2, 3 ...
n
. Given an ordering of the deck, what is the smallest number of shuffles that could possibly put the deck in that order?
Input
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. Each test case will begin with a single integer
n
(1 ≤
n
≤ 1,000,000) indicating the number of cards in the deck. On the next line will be
n
unique integers
c
(1 ≤
c
≤
n
), with a single space between them, indicating an ordering of the
n
cards. The values
c
are guaranteed to be a permutation of the numbers 1..
n
.
Output
Output a single line with a single integer indicating the minimum number of shuffles that could possibly put the deck in the given order. Output no spaces.
Example
Input:
10
1 2 7 3 8 9 4 5 10 6
Output:
1
Input:
8
2 1 4 3 6 5 8 7
Output:
3
Input:
10
3 8 1 9 4 5 2 7 10 6
Output:
2 | 33,933 |
Do It Wrong, Get It Right (DWRONG)
In elementary school, students learn to subtract fractions by first getting a common denominator and then subtracting the numerators. However, sometimes a student will work the problem incorrectly and still arrive at the correct answer. For example, for the problem
5/4 - 9/12
one can subtract the numbers in the numerator and then subtract the numbers in the denominator, simplify and get the answer. i.e.
5/4 - 9/12 = -4/-8 = 4/8 = 1/2
For a given fraction b/n, your task is to find all of the values a and m, where a≥0 and m>0, for which
a/m - b/n = (a-b) / (m-n)
Input
There will be several test cases in the input. Each test case will consist of a single line with two integers, b and n (1 ≤ b, n ≤ 10
6
) separated by a single space. The input will end with a line with two 0s.
Output
For each case, output all of the requested fractions on a single line, sorted from smallest to largest. For equivalent fractions, print the one with the smaller numerator first. Output each fraction in the form “a/m” with no spaces immediately before or after the “/”. Output a single space between fractions. Output no extra spaces, and do not separate answers with blank lines.
Example Input
9 12
12 14
4 12
0 0
Example Output
0/24 5/20 8/16 8/8 5/4
0/28 9/21 9/7
0/24 3/18 3/6 | 33,934 |
A Terribly Grimm Problem (GRIMM)
Grimm's conjecture states that to each element of a set of consecutive composite numbers one can assign a distinct prime that divides it.
For example, for the range 242 to 250, one can assign distinct primes as follows:
Given the lower and upper bounds of a sequence of composite numbers, find a distinct prime for each. If there is more than one such assignment, output the one with the smallest first prime. If there is still more than one, output the one with the smallest second prime, and so on.
Input
There will be several test cases in the input. Each test case will consist of a single line with two integers, lo and hi (4 ≤ lo < hi ≤ 10
10
), separated by a single space. It is guaranteed that all the numbers in the range from lo to hi inclusive are composite. The input will end with a line with two 0s.
Output
For each test case, output the set of unique primes, in order, all on the same line, separated by single spaces. Output no extra spaces, and do not separate answers with blank lines.
Example Input
242 250
8 10
0 0
Example Output
2 3 61 7 41 13 31 83 5
2 3 5 | 33,935 |
You Win! (YOUWIN)
You just achieved the High Score on your favorite video game! Now, you get to enter your name! You have to use the controller to enter your name, which can be awkward. Here’s how it works:
There are only the 26 capital letters A to Z, in order. There are no numbers, spaces, lower case letters, or any other characters.
Pushing UP or DOWN changes the active letter one letter forward (UP) or backward (DOWN). The active letter starts at A. It will not reset when you move around in the name. It also wraps: UP from Z goes to A, DOWN from A goes to Z.
Pushing LEFT or RIGHT moves the cursor one letter left or right in the current name. Note that once the cursor is at either end of the current name, it cannot move any further in that direction.
Pushing the FIRE button adds the active letter to the name.
For example, consider the name ‘ALMA’. One way you could enter ‘ALMA’ is like this:
This would take 28 button pushes. However, consider entering ‘ALMA’ like this:
This takes only 17 button pushes. Given a name, what is the fewest number of button pushes needed to enter that name? Assume that the active letter starts at A, and that it doesn’t matter where the cursor ends up when you’re done.
Input
There will be several test cases in the input. Each test case will consist of a single string on its own line, with from 1 to 18 capital letters, representing a name that must be entered into the High Score list. The input will end with a line with a single 0.
Output
For each test case, output a single integer representing the smallest number of button pushes needed to enter the name. Output no spaces, and do not separate answers with blank lines.
Example Input
ALMA
YES
0
Example Output
17
21 | 33,936 |
When Does The World End (PONY10)
There is a recently discovered ancient temple, and Daring Do is already exploring it.
She's come across an old Artifact of Power, which just seems to be spouting meaningless numbers. "...82980644837721883829806448..."
Reading the inscription on the wall, it gives an explanation to the artifact:
WE HAVE TAPPED INTO THE UNIVERSAL LIFE FORCE.
WE HEAR THE CLOCK TICKING TOWARD THE END.
CAN YOU HEAR IT?
WHEN THE PROPHESIED NUMBERS ARE SAID THE FORETOLD NUMBER OF TIMES
IT ENDS.
Daring Do doesn't know the prophesied numbers or foretold count, so she moves on with exploring.
She gets more clues while exploring:
The artifact began counting at the beginning of time, starting from 0 and going up 1 step at a time, saying each digit individually.
So when it first began, it went "0123456789101112131415...". Each second, it says the next digit. This means at time t=0, it said "0", at time t=1, it said "1", etc.
The universe will end not on the tick after the prophesied number is said for the final time, it ends on the tick that the prophesied number begins. For instance,
if the prophesied numbers were "01", and the foretold number of times were "2", then the universe would end at time t = 11. See below for more examples.
She's found different things which could be the prophesied numbers, or the foretold number of times, but she's not sure.
Please help her figure out the life time of the universe, if the given pair of a 'foretold count' and 'prophesied numbers' were the true ones.
But, if you take too long, the world might end before you figure it out!
Input Description
The first line is an integer T, indicating the number of test cases to follow.
The following T lines will contain 2 things: a number K, the foretold count, and a string composed of digits, TARGET.
Output Description
For each test case, please determine S, the number of seconds until the prophesied number would be said for the final time.
For test case i, please output "Case #i: S" on an individual line.
Example
Input:
6
1 0
1 00
9 1
2 01
100 25
5555 178
Output:
Case #1: 0
Case #2: 191
Case #3: 22
Case #4: 11
Case #5: 9018
Case #6: 5104196
Explanation of Case #3
The artifact starts "0123456789101112131415
1
617..."
We see that '1' occurs for the 9th time at time t = 22.
Limits
For one test file, T ~= 100000. For the other five files, T ~= 10000
Of the possibilities found by Daring Do, they all seem to follow this limit:
LEN(K) + LEN(TARGET) <= 17.
In other words, if TARGET = "1", then K could potentially be "9999999999999999", but no larger.
whereas if TARGET = "1234567890123456", then K could potentially be "9", but no larger. | 33,937 |
Teaching Hazard (BUD13TLB)
Teaching students is fun but it can often be embarrassing, which I experienced a few days ago. I was taking CSE3021 (Mathematical Analysis for Computer Science) class in my university and in the very first class I was teaching some very basic things. To be specific I was trying to teach students how to find trailing zeroes of n! (factorial n) in base b. And of course many of you know that multiplicity of a prime factor p in n! can be found using the formula
This formula can also be used cleverly to find number of trailing zeroes in n!.
After teaching this formula I showed them how to find number of trailing zeroes in 200! in decimal number system and with an evil smile asked them to find out number of trailing zeroes in 100! in hexadecimal (16-based) number system. I knew that the correct answer is 24 and to my utter surprise I got a correct reply from a student within minutes and so I congratulated him. But a minute later when I checked his script I found that he actually calculated number of trailing zeroes in 100! in decimal (not Hexadecimal) number system and coincidentally that both answers (Trailing zeroes in hexadecimal and decimal number system) were 24. So I was a bit embarrassed and now you have to help me find out why those two answers were same? Given a number n, you will have to find how many pair of bases (b1, b2) are there for which n! (Factorial n) has exactly p trailing zeroes in both base b1 and base b2. Here p is a positive integer not less than x.
Input
Input file contains 1000 lines of inputs. Each line contains two integers n (1 ≤ n ≤ 100000) and x (2 ≤ x ≤ 2500).
Input is terminated by a line containing two zeroes.
Output
For each line of input produce one line of output. This line contains an integer which denotes number of base pairs (b1, b2) so that n! has exactly p trailing zeroes in both bases where p is not less than x. You can assume that inputs will be such that none of the output numbers will exceed 5*10^18 .
Example
Input:
6 2
9 3
0 0
Output:
6
2 | 33,938 |
Boxes (BUD13TLF)
Given n boxes with widths of w1, w2 ... wn and another big box with width W, find how many ways the boxes can be put in the big box. The constraints are:
Of course the summation of widths of the placed boxes should not be greater than W.
The boxes should be placed one by one starting from left without leaving any empty spaces between them. So, the end of the big box may contain empty spaces. But if there is any unplaced box which can be fit in this space, the ordering should be considered invalid (See the explanation for sample case 1).
Two orderings are considered different if in one ordering, one box is in i-th position, but in another ordering, it isn’t.
If two boxes have same widths, they should be considered same.
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts two integers n (1 ≤ n ≤ 100) and W (1 ≤ W ≤ 1000). The next line contains n space separated integers, denoting w1 w2 ... wn (1 ≤ wi ≤ W).
Output
For each case, print the case number first and the result modulo 10007.
Example
Input:
2
3 5
1 2 3
5 10
1 2 2 4 5
Output:
Case 1: 6
Case 2: 30
Notes:
For the first case of the Sample Input, the orderings are
12
13
21
23
31
32
Only 1 or 2 or 3 are not solutions since we can still place another box. | 33,939 |
AM FM (TAP2015A)
Amelia has decided to retire from programming competitions and move to a more peaceful place, away from the noisy city. She dreams of sitting in front of her house to see the sunset over the countryside, while listening on the radio to one of her beloved soap operas. However, before fulfilling her dreams she must solve one last problem, which consists in choosing where she should move.
The countryside where Amelia wants to move to is very large and flat, so much so that it can be represented by an infinite plane on which we imagine a Cartesian coordinate system
(X, Y)
. In this countryside there are
N
radio stations numbered
1
through
N
. The
i
-th radio station transmits its signal from an antenna placed at point
(X
i
, Y
i
)
, having a signal range of
R
i
. This radio station can be tuned in to from any point
(X, Y)
whose distance to the antenna is less or equal to the corresponding range,
i.e.
satisfying:
(X - X
i
)
2
+ (Y - Y
i
)
2
≤ R
i
2
The signals from different radio stations can overlap, but will never interfere with each other. In order to listen to as many soap operas as possible, Amelia wants to place her house at some point within the range of the maximum possible number of radio stations. Now Amelia wants to know, given the description of the countryside, what is the maximum number of radio stations she will be able to tune in to as she sees the sunset over the countryside sitting in front of her house.
Input
There are multiple test cases in the input file. For each test case, the first line contains an integer
N
representing the number of radio stations in the countryside (
1 ≤ N ≤ 100
). Each of the following
N
lines contains three integers
X
i
,
Y
i
and
R
i
representing respectively the coordinates of the antenna and the range of the
i
-th radio station (
-1000 ≤ X
i
, Y
i
≤ 1000
and
1 ≤ R
i
≤ 1000
for
i = 1, 2, ... N
).
Output
For each test case, print one line containing an integer representing the maximum number of radio stations Amelia will be able to tune in to if she optimally chooses where to move to.
Example
Input:
5
-1 0 2
1 0 2
0 -2 1
0 0 1
0 2 1
Output:
4 | 33,940 |
Good kg of Flauta bread (TAP2015B)
The company
Flauta
wants to introduce a new package containing one kg of bread (which curiously shall be sliced bread). As part of the package design team, you have been tasked with designing a nutritional pyramid in accordance to the company's requirements. The nutritional pyramid will be represented by a triangular grid of side
L
, which is an equilateral triangle divided in unitary triangles (
i.e.
equilateral triangles of side one) by drawing lines parallel to the sides of the bigger triangle. For example, in the following figure you can see triangular grids for
L = 4, 5
and
6
.
There are
K
different types of food to be shown on the nutritional pyramid, and each of them will be represented by a horizontal section of the grid. A horizontal section is that part of the pyramid that lies between two lines parallel to the base of the grid, drawn in such a way that they only touch the unitary triangles at their borders, without crossing them. In the following figure three valid horizontal sections can be seen shaded in a grid with
L = 5
.
It is important for the
K
sections in which the nutritional pyramid is divided to be easily seen, and for this reason each of them should be composed of many unitary triangles. However, because the size of the grid is fixed there is a limited number of unitary triangles to distribute among all
K
sections. To make sure that no section is left disproportionately small, you have been asked to find out the maximum number of unitary triangles that can make up the smallest section of the pyramid, if the sections are chosen optimally.
For example, in the following figure three different ways to divide a grid of side
L = 5
in
K = 3
are represented.
The grid on the left has two sections with
9
unitary triangles each, having the other section
7
unitary triangles. In the central grid, the sections have
12
,
9
and
4
unitary triangles, whereas in the grid on the right they have
16
,
8
and
1
. Of these three choices, the best one is then represented by the grid on the left, for it has
7
unitary triangles in its smallest section, while the central grid has
4
unitary triangles and the grid on the right has only
1
such triangle. In fact, the choice of sections represented in the grid on the left of the figure is optimal, as there is no other possible choice of
K = 3
horizontal sections in which the smallest of them has more than
7
unitary triangles.
The company Flauta wants to introduce a new package containing one kg of bread (which curiously shall be sliced bread). As part of the package design team, you have been tasked with designing a nutritional pyramid in accordance to the company's requirements. The nutritional pyramid will be represented by a triangular grid of side L, which is an equilateral triangle divided in unitary triangles (i.e. equilateral triangles of side one) by drawing lines parallel to the sides of the bigger triangle. For example, in the following figure you can see triangular grids for L = 4, 5 and 6.
There are K different types of food to be shown on the nutritional pyramid, and each of them will be represented by a horizontal section of the grid. A horizontal section is that part of the pyramid that lies between two lines parallel to the base of the grid, drawn in such a way that they only touch the unitary triangles at their borders, without crossing them. In the following figure three valid horizontal sections can be seen shaded in a grid with L = 5.
It is important for the K sections in which the nutritional pyramid is divided to be easily seen, and for this reason each of them should be composed of many unitary triangles. However, because the size of the grid is fixed there is a limited number of unitary triangles to distribute among all K sections. To make sure that no section is left disproportionately small, you have been asked to find out the maximum number of unitary triangles that can make up the smallest section of the pyramid, if the sections are chosen optimally.
For example, in the following figure three different ways to divide a grid of side L = 5 in K = 3 are represented.
The grid on the left has two sections with 9 unitary triangles each, having the other section 7 unitary triangles. In the central grid, the sections have 12, 9 and 4 unitary triangles, whereas in the grid on the right they have 16, 8 and 1. Of these three choices, the best one is then represented by the grid on the left, for it has 7 unitary triangles in its smallest section, while the central grid has 4 unitary triangles and the grid on the right has only 1 such triangle. InThe company Flauta wants to introduce a new package containing one kg of bread (which curiously shall be sliced bread). As part of the package design team, you have been tasked with designing a nutritional pyramid in accordance to the company's requirements. The nutritional pyramid will be represented by a triangular grid of side L, which is an equilateral triangle divided in unitary triangles (i.e. equilateral triangles of side one) by drawing lines parallel to the sides of the bigger triangle. For example, in the following figure you can see triangular grids for L = 4, 5 and 6.
There are K different types of food to be shown on the nutritional pyramid, and each of them will be represented by a horizontal section of the grid. A horizontal section is that part of the pyramid that lies between two lines parallel to the base of the grid, drawn in such a way that they only touch the unitary triangles at their borders, without crossing them. In the following figure three valid horizontal sections can be seen shaded in a grid with L = 5.
It is important for the K sections in which the nutritional pyramid is divided to be easily seen, and for this reason each of them should be composed of many unitary triangles. However, because the size of the grid is fixed there is a limited number of unitary triangles to distribute among all K sections. To make sure that no section is left disproportionately small, you have been asked to find out the maximum number of unitary triangles that can make up the smallest section of the pyramid, if the sections are chosen optimally.
For example, in the following figure three different ways to divide a grid of side L = 5 in K = 3 are represented.
The grid on the left has two sections with 9 unitary triangles each, having the other section 7 unitary triangles. In the central grid, the sections have 12, 9 and 4 unitary triangles, whereas in the grid on the right they have 16, 8 and 1. Of these three choices, the best one is then represented by the grid on the left, for it has 7 unitary triangles in its smallest section, while the central grid has 4 unitary triangles and the grid on the right has only 1 such triangle. In fact, the choice of sections represented in the grid on the left of the figure is optimal, as there is no other possible choice of K = 3 horizontal sections in which the smallest of them has more than 7 unitary triangles.The company Flauta wants to introduce a new package containing one kg of bread (which curiously shall be sliced bread). As part of the package design team, you have been tasked with designing a nutritional pyramid in accordance to the company's requirements. The nutritional pyramid will be represented by a triangular grid of side L, which is an equilateral triangle divided in unitary triangles (i.e. equilateral triangles of side one) by drawing lines parallel to the sides of the bigger triangle. For example, in the following figure you can see triangular grids for L = 4, 5 and 6.
There are K different types of food to be shown on the nutritional pyramid, and each of them will be represented by a horizontal section of the grid. A horizontal section is that part of the pyramid that lies between two lines parallel to the base of the grid, drawn in such a way that they only touch the unitary triangles at their borders, without crossing them. In the following figure three valid horizontal sections can be seen shaded in a grid with L = 5.
It is important for the K sections in which the nutritional pyramid is divided to be easily seen, and for this reason each of them should be composed of many unitary triangles. However, because the size of the grid is fixed there is a limited number of unitary triangles to distribute among all K sections. To make sure that no section is left disproportionately small, you have been asked to find out the maximum number of unitary triangles that can make up the smallest section of the pyramid, if the sections are chosen optimally.
For example, in the following figure three different ways to divide a grid of side L = 5 in K = 3 are represented.
The grid on the left has two sections with 9 unitary triangles each, having the other section 7 unitary triangles. In the central grid, the sections have 12, 9 and 4 unitary triangles, whereas in the grid on the right they have 16, 8 and 1. Of these three choices, the best one is then represented by the grid on the left, for it has 7 unitary triangles in its smallest section, while the central grid has 4 unitary triangles and the grid on the right has only 1 such triangle. In fact, the choice of sections represented in the grid on the left of the figure is optimal, as there is no other possible choice of K = 3 horizontal sections in which the smallest of them has more than 7 unitary triangles.
Input
There are multiple test cases in the input file. Each test case consists of one line containing two integers
L
and
K
, respectively representing the length of the side of the triangular grid and the number of sections in which said grid is to be divided (
1 ≤ K ≤ L ≤ 10
6
).
Output
For each test case, print one line containing an integer representing the maximum number of unitary triangles that can make up the smallest horizontal section.
Example
Input:
5 3
5 2
1000000 1
1000000 30000
Output:
7
9
1000000000000
32679639 | 33,941 |
CompuTenis reloaded (TAP2015C)
You may remember from a previous edition of TAP about CompuTenis, that sport specially adapted to a public without any mensurable physical qualities and whose rules involve coding with your elbow glued to your ear. This time we will have another problem concerning this exciting subject, in case you found the solution to that one too easy.
Once more, for the purposes of this problem the only thing you have to know about CompuTenis is that two players, which we will call A and B, compete in a match. The match is won by the player who first wins
S
sets, each set being composed of one or more games. In each set the two players play as many games as is required for one of them to win in at least
J
games, with a difference of at least
D
games won in excess of his opponent. The player satisfying both of these conditions is then the winner of the corresponding set.
The Modern Club Association (MCA) has recently found a trove of records of pre-historic CompuTenis matches. Each record consists of a string composed of
N
characters
'
A
'
or
'
B
'
, indicating which player won each of the
N
games the match had, in the order in which they occurred. Now the MCA wants to know, for each record, what the result of the match was.
Input
There are multiple test cases in the input file. For each test case, the first line contains four integers
N, S, J
and
D
. The value
N
represents the number of games in the record to be analyzed (
1 ≤ N ≤ 10
5
). The value
S
indicates the number of sets a player is required to win in order to win the match (
1 ≤ S ≤ 10
). The value
J
is the minimum number of games it is necessary to win in order to win a set, whereas the value
D
indicates that a player should win at least that number of games more than his opponent in order to win the set (
1 ≤ D ≤ J ≤ 100
). The second line contains a string composed of
N
characters
'
A
'
or
'
B
'
. The
i
-th character of the string indicates which player won the
i
-th game played in the match. The input string will represent a valid record of a complete match.
Output
For each test case, print a single line containing two integers representing the number of sets won by player A and player B, respectively.
Example
Input:
10 5 2 1
AAAAAAAAAA
21 3 3 2
AABABBBABBBABABABBABB
Output:
5 0
1 3 | 33,942 |
Happiness for all (TAP2015D)
The separatist state of Nlogonia has
N
cities numbered
1
through
N
. Some pairs of cities are connected by highways, so that if there is a highway between city
A
and city
B
it is possible to travel from
A
to
B
or from
B
to
A
. We say that a citizen from city
i
can visit another from city
j
if there exists a sequence of different cities
c
1
, c
2
... c
m
with
m ≥ 2
such that
c
1
= i
,
c
m
= j
and there is a highway between cities
c
k
and
c
k+1
for
k = 1, 2 ... m-1
.
The people of Nlogonia are very sociable, so they have friends in all the cities they can visit. However, they are also a bit lazy, so that they are not happy unless they can visit each of their friends by taking exactly one highway directly from their city to their friend's.
To avoid Nlogonia's scission, the queen has decided to perform a number of infrastructure works in order to make all of its citizens happy. One possibility consists in building new highways between the cities of Nlogonia, incurring in a cost of
R
per new highway built. Because building many highways can be very expensive, another possibility is to build stadiums in some of Nlogonia's cities. The building of a stadium costs
E
, and immediately makes all the citizens happy in the city where it is built. Then again, you should know that Nlogonia's inhabitants are furthermore somewhat jealous, so that they shall never be happy if there is no stadium in their own city, but there is one in some of their friend's cities. Can you help the queen calculate the minimum cost of the construction work necessary to make everyone in Nlogonia happy?
Input
There are multiple test cases in the input file. For each test case, the first line contains four integers
N, M, R
and
E
. The number
N
represents the number of cities in Nlogonia (
2 ≤ N ≤ 1000
),
M
represents the original number of highways (
1 ≤ M ≤ 10
5
), whereas
R
and
E
represent the cost of building a highway and a stadium, respectively (
1 ≤ R, E ≤ 1000
). Each of the following M lines describes a different highway using two integers
A
and
B
, representing the cities connected by said highway (
1 ≤ A, B ≤ N
with
A ≠ B
).
Output
For each test case, print one line containing an integer representing the minimum cost of the construction work necessary to make everyone in Nlogonia happy.
Example
Input:
9 6 11 12
1 2
3 2
4 5
5 6
6 7
9 7
Output:
71 | 33,943 |
Perfect packing (TAP2015E)
One of the most difficult stages to automate in an industrial cookie production line is the one corresponding to packing. The goal is to design an apparatus capable of counting a precise number
G
of cookies to be put in a package, and the challenge resides in the fact that the cookies may have markedly different shapes,
e.g.
of various animals.
In the cookie factory where you work the design team has been unable to overcome these difficulties. The best design they have achieved corresponds to a counting machine which, when activated, can select
C
i
cookies with probability
P
i
for
i = 1, 2, ..., K
. Having already spent the entire budget allocated to this task, you will have to find a way to make something useful out of this.
Fortunately, you have come up with the following idea to save the project. You shall build an automated packager using
N
counting machines such as the one described above, along with a special regulating software that will perform the following process iteratively. Before starting the first iteration the
N
counting machines are activated, each one selecting certain number of cookies. In each iteration, the software will choose a non-empty subset
S
of the
N
machines such that the sum of the selected cookies is as close as possible to the desired value
G
(in the sense that the absolute value of the difference between this number and
G
is minimum). If there is more than one subset satisfying this condition, the software will choose as
S
any of them with uniform probability. The cookies selected by the counting machines in
S
will then be removed and packed together. Finally, each of the machines in
S
will be activated again in order for it to select certain number of cookies, while the counting machines not in
S
remain unaltered (that is, with the number of cookies they selected in the previous iteration). This process will be repeated until the desired number
M
of packages has been obtained.
For example, let's assume there are
N = 3
counting machines, which we will call
m
1
, m
2
and
m
3
, having each of them the possibility to select
C
1
= 1
or
C
2
= 2
cookies with probability
P
1
= P
2
= ½
. If we want to produce
M = 2
packages with
G = 5
cookies per package, a possible turn of events is the following. Before starting, the three machines select
C
2
= 2
cookies each (this will happen with probability
½ * ½ * ½ = ⅛
). In the first iteration, the software can then choose among the subsets
{m
1
, m
2
, m
3
}
,
{m
1
, m
2
}
,
{m
1
, m
3
}
and
{m
2
, m
3
}
, each with probability
¼
because they all have a difference of one cookie with the desired number
G = 5
. Supposing that the subset
S = {m
2
, m
3
}
is chosen, then the four cookies selected by machines
m
2
and
m
3
will be packed together. These machines will then be activated again, resulting for example in
m
2
selecting
C
1
= 1
cookie and
m
3
selecting
C
2
= 2
cookies (which will occur with probability
½ * ½ = ¼
). At this point the first iteration ends, the counting machines
m
1
,
m
2
and
m
3
having selected
2, 1
and
2
cookies respectively. In the second iteration, the software must necessarily choose the subset
S = {m
1
, m
2
, m
3
}
as it contains exactly five cookies, which will therefore be packed together. Finally, the three counting machines will be activated once more and the process will end, having produced the
M = 2
desired packages. Note that the net probability for the process here described is
⅛ * ¼ * ¼ = 1/128
, and that the average number of cookies per package is in this case
4.5
(because two packages were produced, one of them having four and the other five cookies).
Your boss is not completely convinced that this system will work, so he requires from you some concrete proof of concept. To convince him, it will suffice to calculate the expected number of cookies per package after producing
M
packages consecutively, if you assume that the
N
counting machines always select cookies according to the given probabilities.
Input
There are multiple test cases in the input file. For each test case, the first line contains four integers
N, K, G
and
M
. The value
N
represents the number of counting machines to use (
1 ≤ N ≤ 4
),
K
represents the number of possible quantities of cookies each counting machine can select (
1 ≤ K ≤ 6
),
G
represents the desired number of cookies per package (
1 ≤ G ≤ 100
), and
M
represents the total number of packages to produce (
1 ≤ M ≤ 10
7
). Each of the following
K
lines contains an integer
C
i
and a rational
P
i
, indicating that the counting machines will select
C
i
cookies with probability
P
i
(
1 ≤ C
i
≤ 100
and
0 < P
i
≤ 1
for
i = 1, 2, ..., K
, being
P
i
given with exactly two digits after the decimal marker). Note that
C
i
≠ C
j
for
i ≠ j
and that
∑ P
i
= 1
.
Output
For each test case, print one line containing a rational representing the expected number of cookies per package after having produced
M
packages as described in the problem statement. Print the result with exactly
6
digits after the decimal marker, rounding if necessary.
Example
Input:
3 2 5 1
1 0.50
2 0.50
3 2 5 2
1 0.50
2 0.50
Output:
4.312500
4.327148 | 33,944 |
Induced favoritism (TAP2015F)
In a kingdom far, far away there are N cities numbered 1 through N, some pairs of cities being connected by roads. When two cities are directly connected by a road, we will say these cities are neighbors. As a result of the careful planning of its monarchs, the kingdom's road system has very special characteristics. We know there are no two cities connected by more than one road, and that all roads connect different cities. Another very peculiar property of the roads is that there is exactly one path between any two cities, consisting of a sequence of roads connecting neighboring cities from the initial to the final one.
In this kingdom far, far away, the king wants to impose curling as the national sport. He therefore wants each city to have a favorite curling team, so that the feeling of belonging of its citizens is enhanced by all of them supporting the same team. There are some cities which already have a favorite team, and because curling is a deep passion these choices cannot be changed. However, other cities don't yet have a favorite curling team, so one will have to be assigned to them in order for it to become the city's favorite.
The president of the Institute for the Competitive Practice of Curling (ICPC) has requested your help, because the king has entrusted it with assigning the favorite teams for the cities that don't yet have one. The problem is that there are too many cities in the kingdom, so the ICPC doesn't really know how to complete this task. We know there are E curling teams which have been numbered 1 through E, and there is no budget to create more. The ICPC has provided you with a riot index between teams for every pair of teams, i.e. an integer D[i, j] representing the degree of hostility between followers of teams i and j, for i, j = 1, 2, ..., E. Note that there even exists a riot index for a given team with itself, as it is possible that inhabitants of two neighboring cities with the same favorite team start to fight in order to see which one has the best following.
The ICPC has asked you to assign a favorite team to every city in the kingdom not having one yet, in such a way that the riots between neighboring cities are minimized. In order to do this, you should minimize the national riot index, which is calculated by summing all the riot indices for teams assigned to neighboring cities. Can you help the ICPC determine the minimum possible value of the national riot index?
In a kingdom far, far away there are
N
cities numbered
1
through
N
, some pairs of cities being connected by roads. When two cities are directly connected by a road, we will say these cities are neighbors. As a result of the careful planning of its monarchs, the kingdom's road system has very special characteristics. We know there are no two cities connected by more than one road, and that all roads connect different cities. Another very peculiar property of the roads is that there is exactly one path between any two cities, consisting of a sequence of roads connecting neighboring cities from the initial to the final one.
In this kingdom far, far away, the king wants to impose curling as the national sport. He therefore wants each city to have a favorite curling team, so that the feeling of belonging of its citizens is enhanced by all of them supporting the same team. There are some cities which already have a favorite team, and because curling is a deep passion these choices cannot be changed. However, other cities don't yet have a favorite curling team, so one will have to be assigned to them in order for it to become the city's favorite.
The president of the
Institute for the Competitive Practice of Curling
(ICPC) has requested your help, because the king has entrusted it with assigning the favorite teams for the cities that don't yet have one. The problem is that there are too many cities in the kingdom, so the ICPC doesn't really know how to complete this task. We know there are
E
curling teams which have been numbered
1
through
E
, and there is no budget to create more. The ICPC has provided you with a riot index between teams for every pair of teams,
i.e.
an integer
D
ij
representing the degree of hostility between followers of teams
i
and
j
, for
i, j = 1, 2, ..., E
. Note that there even exists a riot index for a given team with itself, as it is possible that inhabitants of two neighboring cities with the same favorite team start to fight in order to see which one has the best following.
The ICPC has asked you to assign a favorite team to every city in the kingdom not having one yet, in such a way that the riots between neighboring cities are minimized. In order to do this, you should minimize the national riot index, which is calculated by summing all the riot indices for teams assigned to neighboring cities. Can you help the ICPC determine the minimum possible value of the national riot index?
Input
There are multiple test cases in the input file. For each test case, the first line contains two integers
N
and
E
, representing respectively the number of cities and the number of curling teams in the kingdom (
2 ≤ N ≤ 5 * 10
4
and
1 ≤ E ≤ 50
). The following
E
lines describe the riot indices between the curling teams. Each of these lines contains
E
integers, the
j
-th integer of the
i
-th of these lines being
D
ij
, the riot index between teams
i
and
j
(
0 ≤ D
ij
≤ 1000
with
D
ij
= D
ji
for
i, j = 1, 2, ..., E
).
The following
E
lines describe the favorite teams of the cities which have already chosen one. The
i
-th of these lines starts with a non-negative integer
K
i
followed by a list of
K
i
cities whose favorite team is number
i
(
0 ≤ K
i
≤ N
for
i = 1, 2, ..., E
). No city has more than one favorite team, and there are no repeated cities in the lists.
The last
N-1
lines describe the roads between the kingdom's cities. Each of them contains two integers
A
and
B
, indicating that there is a road between city
A
and city
B
(
1 ≤ A, B ≤ N
with
A ≠ B
). The roads are bidirectional and there are no repeated roads in the input. It is guaranteed that there is a unique path between every pair of cities, possibly going through other intermediate cities.
Output
For each test case, print one line containing an integer representing the minimum value of the national riot index that can be achieved by optimally assigning the favorite teams.
Example
Input:
3 2
2 1
1 2
0
0
1 2
1 3
6 3
3 2 1
2 3 4
1 4 3
2 1 3
0
0
1 2
1 3
1 4
3 5
3 6
Output:
2
7 | 33,945 |
Generating alien DNA II (TAP2015G)
There is a fundamental and unchanging characteristic shared by all life on Earth, from the tiniest microbe to whales, dinosaurs and human beings: DNA. This is the only known mechanism for the transmission and replication of genetic information, which poses one of the most important questions in modern biology: is DNA the only way to encode this information, or are there other possible mechanisms?
Professor Gould is a theoretical exobiologist whose research considers the possibility of the existence of extra-terrestrial life not having its genetic information encoded as DNA. Presently, he is developing a model based on the encoding of genetic information in the form of a chain of pseudo-nucleotides, which we will represent with the characters
'b', 'd', 'o', 'p', 'q', 'v', 'w'
and
'x'
. Each pseudo-nucleotide has a conjugate:
'o', 'v', 'w'
and
'x'
are each its own conjugate, whereas
'b'
is the conjugate of
'd'
,
'p'
is the conjugate of
'q'
, and conversely
'd'
is the conjugate of
'b'
and
'q'
is the conjugate of
'p'
.
In the model developed by professor Gould, an organism can suffer a mutation starting from a given position in its pseudo-nucleotide chain, resulting in the inversion and conjugation of the second part of said chain. Specifically, if the original pseudo-nucleotide chain is
a
1
a
2
... a
N
and the mutation occurs starting from position
i
, the resulting pseudo-nucleotide chain is
a
1
a
2
... a
i-1
ã
N
ã
N-1
... ã
i+1
ã
i
, where
ã
k
represents the conjugate of the pseudo-nucleotide originally at position
k
.
As it evolves, an organism may suffer many mutations in this manner, the only restriction being that successive mutations should occur starting from positions which are ever closer to the end of the pseudo-nucleotide chain. For example, the chain "
bdopqvwx
" can suffer a mutation starting from position
3
resulting in the chain
"bdxwvpqo"
, and after that another mutation starting from position
7
giving thus the chain "
bdxwvpop
", but these two mutations couldn't have occurred the other way around.
At this point in his research, professor Gould has two pseudo-nucleotide chains which are particularly interesting, and he would like to know the minimum number of mutations the first of them must suffer in order to become the second one. Can you help him?
Input
There are multiple test cases in the input file. For each test case, the first line contains an integer
N
, representing the length of both pseudo-nucleotide chains to be analyzed (
1 ≤ N ≤ 1000
). Each of the following two lines contains a string of
N
characters
'b', 'd', 'o', 'p', 'q', 'v', 'w'
and
'x'
, representing a pseudo-nucleotide chain.
Output
For each test case, print one line containing an integer representing the minimum number of mutations the first chain in the input should suffer in order to become the second one. If this is not possible, print the number
-1
.
Example
Input:
8
bdopqvwx
bdxwvpop
5
bdopq
bdopq
10
ddbbddbbdd
bbddbbddbb
13
opoqpvbdxwwbp
vwpopvxxbdpqq
Output:
2
0
1
-1 | 33,946 |
Hugo s homework (TAP2015H)
Hugo goes to primary school, but he is convinced that not enough homework is being given to him. Specifically, he was recently taught how to subtract two numbers, but each day he is given a single subtraction to perform at home. Hugo knows that in order to master such a complex technique he should practice much more, so he has decided to take matters into his own hands and create his own homework.
It's not easy for Hugo to invent exercises about a subject he does not fully comprehend, so he has devised the following method to perform multiple subtractions. He starts by asking his mother for a number
N
, and then forms the number
M
containing the same digits as
N
in increasing order from left to right, after which he finally performs the subtraction
N-M
. For example, if his mother chooses the number
N = 321
then
M = 123
and the subtraction Hugo must perform is
N - M = 321-123 = 198
.
Hugo wouldn't want to bother his mother too often, so he will repeat this procedure using the result of the subtraction
N-M
in one step as the number
N
he starts with in the next step. This will end only when at some point he reaches the value
N = 0
, as this case is useless to practice subtractions because he would have
M = 0
: Hugo already knows perfectly well that if he has no candies he cannot eat any candies, and will therefore continue to not have or eat candies forever.
Now Hugo's mother would like to know, given a number
N
, how many subtractions Hugo can perform if she gives him that number to start his homework. In the previous example, in the second step Hugo would have
N = 198
so that
M = 189
and
N - M = 198 - 189 = 9
. Then in the third step
N = 9
,
M = 9
and
N - M = 0
, so here the fun ends because in the fourth step he would have
N = 0
. Thus, starting with the number
N = 321
Hugo will perform
3
subtractions.
Input
There are multiple test cases in the input file. Each test case consists of one line containing an integer
N
, representing the number Hugo's mother will give him to start his homework (
1 ≤ N ≤ 10
9
).
Output
For each test case, print one line containing one integer representing the number of subtractions Hugo will perform if he starts his homework with number
N
.
Example
Input:
321
20
960687301
Output:
3
2
91 | 33,947 |
Invading aliens (TAP2015I)
In the novel
"A for Andromeda"
, by Fred Hoyle and John Elliot, a civilization from a planet in orbit around a star in the constellation of Andromeda, 200 light years away from our Solar System, decides to colonize the galaxy. To avoid the long and costly interstellar travels, this civilization decides to perform the colonization at a distance, by sending a signal instead of ships (this signal contains instructions on how to build a supercomputer with an artificial intelligence capable of taking over the world of the unfortunate civilizations who build it, but that is not our problem for the moment).
One of the issues humans have to overcome in order to construct the supercomputer is the decoding of the signal. As it happens, the aliens send two messages in two different frequencies, repeating endlessly in each of them a code with
N
characters. For example, if
N = 3
and one of the codes is
"
abc
"
, the alien message in the corresponding frequency will be
"...
cabcabcabcab
..."
, where the ellipsis mean that the code is repeated infinitely both backwards and forwards. For this reason, the terrestrial stations receiving the signal are incapable of telling what the emitted code actually is, as there can be more than one code that is compatible with a given message. In our example, knowing that
N = 3
they could interpret that the code is any of three possibilities
"
abc
"
,
"
bca
"
and
"
cab
"
.
Complicating matters even further, although both messages are composed solely of characters from the alphabet
'
a
'
through
'
z
'
, because they are transmitted in different frequencies there exists an ambiguity in the identification of the characters between them. Thus, if we let the characters be named
c
1
= '
a
'
,
c
2
= '
b
'
, and so on until
c
26
= '
z
'
, it is possible that every occurrence of the character
c
i
in one of the messages is replaced by the character
c
σ(i)
in the other message, where
σ(i)
is an arbitrary permutation of the numbers from
1
to
26
. For instance, if we have
σ(1) = 24
,
σ(2) = 25
and
σ(3) = 26
the code
"
abc
"
in one of the frequencies will be turned in the other into
"
xyz
"
, so that the corresponding message will be
"...
zxyzxyzxyzxy
..."
.
You've been put in charge of decoding the alien signal, and your task is to determine the maximum length of a common substring that two codes compatible with the received messages can have. This is, you should find the maximum value
K
such that one of the messages is compatible with the code
a
1
a
2
... a
N
and the other is compatible with the code
b
1
b
2
... b
N
, and there exist
i
and
j
with
0 ≤ i
,
j ≤ N-K
such that
a
i+k
= b
j+k
for
k = 1, ..., K
up to a permutation of the alphabet.
Input
There are multiple test cases in the input file. For each test case, the first line contains an integer
N
representing the length of the codes emitted by the aliens (
1 ≤ N ≤ 1000
). Each of the two following lines contains the description of the message received in a different frequency, in the form of a string of
N
characters from
'
a
'
to
'
z
'
. The received message is obtained repeating endlessly the corresponding string.
Output
For each test case, print one line containing an integer representing the maximum length of a common substring two codes which are compatible with the received messages can have.
Example
Input:
3
abc
xyz
3
aab
cdd
4
abab
xyzw
4
xyzw
abab
18
imzbyqlgjwrvfspthe
rubihyvjnomqdznhat
Output:
3
3
2
2
16 | 33,948 |
Game of stones II (TAP2015J)
Jaimito didn't waste any time since he was offered his stones in 2013. He no longer spends his time playing with his mother Jimena to games in which his victory is guaranteed, for he explored many stone game variants, as every child should. He even became very good at some of these games, and took part in various championships obtaining excellent results.
For a few months now, he has been particularly interested in a game of stones called
TArros con Piedras
(TAP). In this game there are
N
jars with stones inside, and two players take turns to play. In his turn, each player should take one stone from one jar, two stones from another jar, and three stones from a third one, and so on until taking
N
stones from some jar, so that the player takes stones from every jar in a single turn. The game continues in this way until one of the players cannot take stones from the jars in a valid way in his turn. Said player loses the match, the other player being the winner.
For example, consider a match with
N = 3
jars with one of them initially having
P
1
= 3
stones, another one having
P
2
= 4
stones and the third one having
P
3
= 10
stones. In this match the player who starts playing has a winning strategy, as he can take one stone from the jar originally having ten stones, two stones from the jar which had three stones, and finally three stones from the jar that initially had four stones. He would then leave the jars with
P
1
= 1
,
P
2
= 1
and
P
3
= 9
stones, so that the second player cannot take stones from the jars in a valid way.
Jaimito is taking part in a TAP championship, and he has reached the finals, where he will face Jacinta. Both of them are expert players, so they make no mistakes when they play. Jaimito has told his mother everything about the match,
i.e.
the number
N
of jars and how many stones each of them will start with. Jimena knows Jacinta will start playing, and she would like to know if her son will win the championship, but she can't figure it out because she is too nervous to think properly. Can you help her?
Input
There are multiple test cases in the input file. For each test case, the first line contains an integer
N
representing the number of jars in the match (
1 ≤ N ≤ 10
5
). The second line contains
N
integers
P
i
representing the number of stones in each jar before starting the match (
1 ≤ P
i
≤ 10
9
for
i = 1, 2, ... N
).
Output
For each test case, print a line containing a character indicating if Jaimito will win the finals or not. The printed character should be an
'
S
'
if Jaimito is to win, otherwise it should be an
'N'
.
Example
Input:
3
3 4 10
2
10 3
Output:
N
S | 33,949 |
Kimetto Kipsang and Kipchoge (TAP2015K)
Kenya is the birthplace of some of the best long-distance runners of all times. Indeed, eight of the most recent ten best times in the traditional 41.195 km of the marathon have been set by runners from that country. Dennis Kimetto, Wilson Kipsang and Eliud Kipchoge are three such runners, and they want to beat their discipline's world record once more tomorrow September 27, when they compete in the 42
nd
edition of the Berlin Marathon.
Kimetto, Kipsang and Kipchoge are good friends, and they like to train together running by the Tana river in order to appreciate the beautiful trees that grow there. There are
N
trees by the river, which we will number from
1
to
N
. The
i
-th tree is of the species
S
i
and stands at a distance of
i
meters from the mouth of the river. Our three runners are especially motivated by the sight of many trees of different species. For this reason, each training day they choose a tree with number
K
from
1
to
N
, and then run from the
K
-th tree following the river,
i.e.
in the direction of trees
K-1
,
K-2
and so on, stopping only when they see a tree of some species they have already seen that day, or when they reach the mouth of the river, whichever comes first.
For example, if there are
N = 4
trees of species
S
1
= 1
,
S
2
= 2
,
S
3
= 1
and
S
4
= 3
, when they choose
K = 4
the training consists in running
3
meters, from tree number
4
up to tree number
1
(where they stop because this tree is of the same species as tree number
3
). However, if they chose
K = 2
they would run two meters up to the mouth of the river, where they would stop even without having seen two trees of the same species as they went.
Long-distance running requires decades of training, and in this time it is common for some trees to fall during storms. When this happens, the fallen tree is immediately replaced by another one, not necessarily of the same species. Kimetto, Kipsang and Kipchoge keep a diary where they take note of all the information relevant to their training. In particular, they know the species of all trees, and which number they chose to start running each day of training. Can you help them calculate how much they ran each training day?
Input
There are multiple test cases in the input file. For each test case, the first line contains two integers
N
and
R
, representing respectively the number of trees by the river and the number of entries in the training diary (
1 ≤ N, R ≤ 5 × 10
4
). The second line contains
N
integers
S
i
indicating the species of the
i
-th tree when the training began (
1 ≤ S
i
≤ 10
6
for
i = 1, 2, ..., N
). Each of the following
R
lines contains the description of an entry in the training diary, in chronological order. This description starts with a character which can be a
'
C
'
if the entry corresponds to a fallen tree or an
'
E
'
if it corresponds to a training day. The entries for fallen trees contain two integers
K
and
S
after the
'
C
'
, indicating that the
K
-th tree fell and was replaced by another tree of species
S
(
1 ≤ K ≤ N
and
1 ≤ S ≤ 10
6
). The entries for training days contain an integer
K
after the
'
E
'
, indicating that the runners began a training day by running from the
K
-th tree (
1 ≤ K ≤ N
). There will always be at least one entry for a training day in each test case.
Output
For each test case, print one line for each entry corresponding to a training day, indicating the number of meters Kimetto, Kipsang and Kipchoge ran during that day.
Example
Input:
4 2
1 2 1 3
E 4
E 2
10 10
1 2 3 4 5 6 7 8 9 10
E 1
E 2
E 3
E 4
E 5
E 6
E 7
E 8
E 9
E 10
5 7
1 2 3 4 5
E 3
E 5
C 3 1
E 4
C 2 5
E 3
E 5
Output:
3
2
1
2
3
4
5
6
7
8
9
10
3
5
3
2
3 | 33,950 |
LUTRIJA (LUTRIJA)
You are given a
cactus graph
of N nodes and M edges.
Compute number of simple paths of length L, for each L between 1 and N, modulo 10
9
+ 7. Here path length is number of nodes on it.
Input
First line consists of two integers, N (1 <= N <= 4000) and M (0 <= M <= 100 000).
Each of next M lines consists of two integers a and b (1 <= u < v <= N) which represents bidirectional edge between nodes u and v.
Every pair (u, v) appears at most once in edges list.
Note: graph need not be connected.
Output
Output N integers in one line as described above.
Example
Input:
3 3
1 3
2 3
1 2
Output:
3 6 6 | 33,951 |
Factorial Modulo (FCDC)
You are given 2 integers a, b. Find the number of i for which i! is divisible by a but not b. if i! is divisible by a and b, then you should not count that i.
Input
One line that contains a and b.
Output
Output the result in one line.
Example
Input:
2 3
Output:
1
Constraints
1 ≤ a ≤ b ≤ 10
7
Explanation
2! is the only factorial which is divisible by 2 and not divisible by 3. | 33,952 |
Hablu Wants to Buy (HMBY)
In Hablu's country, there are 5 types of notes. $2, $4, $8, $16 and $32. He went to a shop, and wants to buy an item which costs $w. He has to pay exactly $w to the shopkeeper. Can he pay $w?
Hablu can break his notes in half, that is, he can break his one $32 notes to two $16 notes, a $16 can be broken into two $8 notes, and so on. Only $2 can't be broken into $1, because there are no $1 notes. He has A $2 notes, B $4 notes, C $8 notes, D $16 notes and E $32 notes. Your task is to find whether Hablu can pay $w using his notes.
Input
The first and only line contains positive integers A, B, C, D, E, w, separated by spaces.
Output
If Hablu can pay $w, print "YES", else print "NO".
Example
Input:
1 2 3 4 5 2
Output:
YES
Constraints
(A+B+C+D+E) ≤ 10
9
w ≤ 10
7 | 33,953 |
Jolly Kingdom (JOLLYKINGDOM)
Jolly Kingdom is a kingdom which is famous for its troops' power. Jolly Kingdom has N swordsman troops and M archer troops where each troop has his/her own unique fighting style, different with others.
For the 10
th
times, an evil witch with her monster troops tries to seize the throne of Jolly Kingdom. According to the information gathered from Jolly Kingdom's spies, the witch will attack everyday for H days. Each day, the witch will add 1 new monster into her monster troops. This makes enemy's troops become stronger every day.
Each monster owned by the witch is strong and almost unbeatable, only the X
i
th
swordsman troop or the Y
i
th
archer troop can beat the monster. After the monster has been defeated by Jolly Kingdom's troop, that monster will take a reset and attack again in the next day.
To protect Jolly Kingdom, every day
all monsters
have to be defeated, but the cost to send 1 troop is expensive, so the king wants to send minimum number of troops every day such that the sent troops will be able to defeat
all monsters
exist on that corresponding day.
The king asks you for your help, as a royal advisor, the number of troops the king has to send every day.
Input
First line consists of 3 integers: N, M, and H (1 ≤ N, M ≤ 1000; 1 ≤ H ≤ N*M) – the number of swordsman troops, archer troops, and days. Each of next H lines contains 2 integers: X
i
and Y
i
(1 ≤ X
i
≤ N; 1 ≤ Y
i
≤ M) – the weakness of i
th
monster, i
th
can be defeated by the X
i
th
swordsman or Y
i
th
archer.
There can't be 2 monsters with the exact same weakness (there won't be any monster i and j where X
i
= X
j
and Y
i
= Y
j
for all 1 ≤ i, j ≤ H and i ≠ j).
Output
Print H lines. Each line contains 1 number represents the answer to the king's question.
Sample Tests
Input
4 4 9
1 1
1 2
1 3
2 1
4 1
3 4
3 3
4 3
4 4
Output
1
1
1
2
2
3
3
4
4
Explanation for sample case
Notation: { swordsman troop number: monster number(s) defeated } { archer troop number: monster number(s) defeated }
1
st
day: {
1
: 1} {}
2
nd
day: {
1
: 1 2} {}
3
rd
day: {
1
: 1 2 3} {}
4
th
day: {
1
: 1 2 3} {
1
: 4}
5
th
day: {
1
: 1 2 3} {
1
: 4 5}
6
th
day: {
1
: 1 2 3;
3
: 6} {
1
: 4 5}
7
th
day: {
1
: 1 2 3;
3
: 6 7} {
1
: 4 5}
8
th
day: {
1
: 1 2 3;
3
: 6 7;
4
: 8} {
1
: 4 5}
9
th
day: {
1
: 1 2 3;
3
: 6 7;
4
: 8 9} {
1
: 4 5}
Information
The constraints above is not typo, N and M can be as large as 1000 (1 Thousand), so H can be as large as 10
6
(1 Million). So this problem has 10× larger constraints than the original one.
Warning: Large Input/Output files, each file I/O can be as large as 7.5 Megabytes (7.5 MB), cin or cout probably too slow for I/O, it's recommended to use scanf/printf (I've tested it).
If you find this problem too hard, you can try this first:
https://jollybeeoj.com/problem/view/199
original problem with smaller constraints.
Trivia
The total size of file I/O in this problem is slightly more than 100 MB, took a while to generate, modify, and upload it. :)
If the witch attack Jolly Kingdom everyday for 1 Million days that means the attack took more than 2500 years. :o
If I count number of operation in the deepest loop of my algo on worst case input, it will be 671,163,499 operations.
Credit & Special thanks
Sandy Karunia
- Developer of
Jollybee Online Judge
Alvin Setiadi
- Original problem author | 33,954 |
Laser Beam (LASER_BEAM)
5 × 9 grid without laser beam
5 × 9 grid with laser beam
Jolly Kingdom is threatened by the arrival of an evil witch. In order to protect the kingdom, the king wants to install some powerful laser beams to cover some parts of the kingdom. The part that needs to be protected has size of N × M. To complete this installation, he hired you, as the best engineer he can find.
Imagine a grid of size N × M, you can choose one node in the grid and shot a laser beam, the laser can be shot only in diagonal direction as shown in the picture above, if the laser reach the edge of the grid, it'll bounce to other diagonal direction, and if the laser reach the corner of the grid, it'll bounce back. The laser will form a loop track. In order to install the best security laser beam for the king, you have to compute the number of different laser track.
Input
First line consists of an integer T (1 ≤ T ≤ 10
4
) – the number of test cases. Each of next T lines consists an 2 integers N and M (2 ≤ N, M ≤ 10
9
) – the size of the grid.
Output
For each test case, output an integer – the number of different laser track on that grid.
Example
Input:
9
2 2
2 3
3 3
3 5
4 4
5 5
5 9
5 123456789
123456789 5
Output:
2
2
3
3
4
5
5
5
5
Explanation
There are 5 different laser tracks on 5 × 9 grid, shown in the picture above as black line, blue line, pink line, orange line, and green line. | 33,955 |
One of the Simpsons symbols (NNUM)
It’s one of the boring days, and coach Ali decided to turn his TV on and to see something amusing, to his luck they were showing the famous Simpsons series, so he made popcorn and sat to watch it, the episode name was “Marge and Homer Turn a Couple Play” from 2006 season, the episode took part at a baseball court, in the big screen they asked the following multi-choice question:
Can you guess the number of the audience?? With answers:
8128
8191
8208
I can’t guess.
“Numbers???” Shouted Coach Ali, “I wonder are they chosen randomly, or do they refer to something???” You know Simpsons and its weird symbols.
That made him curious so he decided to investigate it, as Ali always says: ”Google is stupid” He decided to use the Syrian search engine, Shamra.sy and Shamra gave him the answer in a blink of eye!!! and guess what? Each of these numbers belong to a family of numbers!!!
8128 is called an “Ideal number” (expect to see a problem about this family.)
8191 is called a “prime number” (primes are well known to all.)
8208 is called a “Narcissistic number”.
As Coach Ali loves Greek Methodology he remembered the famous myth of god “Narcisse” so he decided to make extra search about this family, again Shamra gave him the answer in a blink of eye!!! According to Wikipedia: it is a
number
that is the sum of its own digits each raised to the power of the
number
of digits.
For example: 8208 = 8^4+2^4+0^4+8^4 = 4096+16+0+4096
Now Ali is wondering, how many positive Narcissistic numbers consisting of N digits??? As he is busy in studding for the expected “Principles of Electronics” test, he decided to give the problem to his contestants, as part of their training for coming TCPC 2016.
Input
One line, containing N, 1<=N<=8
Output
One line, containing the number of positive Narcissistic numbers consisting of N digits.
Example
Input:
1
Output:
9
Note: As Coach Ali is impatient, the time limit per test for every test case is just 0.1 Seconds. | 33,956 |
Bit Difference (BITDIFF)
Given an integer array of N integers, find the sum of bit differences in all the pairs that can be formed from array elements. Bit difference of a pair (x, y) is the count of different bits at the same positions in binary representations of x and y. For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 (first and last bits differ in two numbers).
Input
Input begins with a line containing an integer
T (1<=T<=100)
, denoting the number of test cases. Then T test cases follow. Each test case begins with a line containing an integer
N (1<=N<=10000)
, denoting the number of integers in the array, followed by a line containing
N
space separated 32-bit integers.
Output
For each test case, output a single line in the format
Case X: Y
, where
X
denotes the test case number and
Y
denotes the sum of bit differences in all the pairs that can be formed from array elements modulo
10000007
.
Example
Input:
1
4
3 2 1 4
Output:
Case 1: 22 | 33,957 |
Cinema Conundrum (CINEMACON)
Adorsho Ingreji Uccho Biddaloy has recently opened Media Studies department. Even though the name of the institute implies otherwise, it offers various courses on Bangla media too. As part of a course called Deshi Movie Analysis, the students of this department has to watch at least
M
minutes of movies that are being shown at various cinema halls across the city and submit their analysis report.
Nadim, a student of this department, thought it would be great at first. How many students get to watch movies for education, right? Wrong! He quickly found out how gravely mistaken he was seeing movie titles like “Toke Valobashtei Hobe” and “Matha Noshto”. He decides to do away with this task as fast as possible.
There are
N
cinema halls situated in a straight line (he lives in one of the most well planned cities in the world) one after another, each showing a different movie. His plan is to, given the length of each movie in minutes, select the least number of movies that will satisfy the M minutes of movie-watching requirement of the course. As he is lazy, he does not want to watch a movie in a hall and then go to a hall far away from the previous one to watch another movie. So, he decides to watch movies in halls so that the hall of a movie is situated next to the hall of the previous movie that he watched, if he watches multiple movies. A person can watch only one movie and only once at a hall any time he wishes. Once a person enters a hall, he cannot leave before finishing the movie.
As stated before, he is lazy and has asked you, his best friend, to help him. You are lazy too, but you are a good programmer. So you decide to write a program.
Input
Input begins with a line containing a single integer
T (1 ≤ T ≤ 100)
, denoting the number of test cases.
T
test cases follow. Each test case begins with a line containing two integers
N (1 ≤ N ≤ 10000)
and
M (0 ≤ M ≤ 10
9
)
, denoting the number of cinema halls(and thus the number of movies) and the minimum movie-watching experience required by the course respectively. The next line contains N space separated positive integers denoting the length of movies in minutes shown in cinema halls from left to right. These integers will not exceed 10
5
.
Output
For each test case, output a single line in the format
Case X: Y
, where
X
denotes the test case number and
Y
denotes the minimum number of movies Nadim has to watch in consecutive cinema halls so that he earns at least M minutes of movie-watching experience. If he cannot complete this task, Y should be
-1
.
Example
Input:
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
Output:
Case 1: 2
Case 2: 3 | 33,958 |
Decreasing Number of Visible Box (VISIBLEBOX)
Shadowman loves to collect box but his roommates Woogieman and Itman don't like box and so Shadowman wants to hide as many boxes as possible. A box can be kept hidden inside another box if and only if the box in which it will be held is empty and the size of the box is at least twice as large as the size of the box.
Print the minimum number of box that can be shown.
Input
The input set starts with single line integer
T (1 ≤ T ≤ 50)
the number of test cases. Then following
T
cases starts with an integer
N (1 ≤ N ≤ 100000)
denoting the number of box. The next line contains
N
space separated positive integer.
i-th
of them contains a numbers
A
i
(1 ≤ A
i
≤ 100000)
size of the
i-th
box.
Output
Output the the case number and the minimum number of box that can be shown.
Example
Input:
2
4
1 2 4 8
4
1 3 4 5
Output:
Case 1: 1
Case 2: 3 | 33,959 |
Fury Road (FURYROAD)
Westland is full of war parties. There is always frequent war occurs in the fury road of Westland. Today is an another great day for the immortal Joe, because he is going to the war with his Kamakrazee war boys in the fury road. So, he sent Slit one of his war boys to count the number of war parties. In the fury road there are multiple war parties fight together, so it is difficult to count the number of war party but, Slit properly know that, if a group of war boys stand together, on the other word if they are adjacent (vertically, horizontally and diagonally) to each other, they would be counted as a single war party. As, there is large number of war parties in the fury road, it is not quite easy to count the number of war parties perfectly. So, Slit needs your help to determine the number of war parties in the fury road.
Now, you are given the number of war boys and their position in the Cartesian plane as (x, y) format which indicates the war boy’s position. Now you have to determine the number of war parties.
Input
The input set starts with single line integer
T (1 ≤ T ≤ 50)
the number of test cases. Then following
T
cases starts with an integer
N (1 ≤ N ≤ 10000)
denoting the number of war boys in the fury road Then next
N
line contains a pair of integer
(X
i
, Y
i
) (0 ≤ X
i
, Y
i
≤ 1000)
denoting the position of i-th war boy.
Output
For each case print “
Case X:
” (without the quotes) where
X (1 ≤ X ≤ T)
is the case number. And then print the number of War parties in the fury road. Every new case should be printed in a new line.
Example
Input:
3
2
5 5
3 2
6
1 3
0 1
1 2
2 3
4 1
5 0
1
0 0
Output:
Case 1: 2
Case 2: 2
Case 3: 1 | 33,960 |
Highly Spiritual Baba (HIGHBABA)
A spiritual baba in Banani claims that, given two strings he can check if one string is available in another string as sub-sequence and not only that, he can even tell the minimum sub-array in which that sub-sequence exists. Now your friend wants to know if that spiritual baba is fraud or not. So, he wants you to make an application for him.
You are given two strings A & B. Now, find the minimum length sub-array of string ’A’ which contains the sub-sequence (string ‘B’). If such sub-sequence cannot be found, print -1.
Subsequence:
suppose a string “abcdef” is given. Here, ”abcdef”, “abf”, “def”, “bce”, “a” are some example of sub-sequence of this string. But strings like “fea” and “dc” are not.
Input
The first line of the input contains an integer
T (1 ≤ T ≤ 100)
number of test cases. For each test case, two strings
A (1 ≤ N ≤ 2500)
and
B (1 ≤ M ≤ 80)
are given, each containing lowercase letter of the English alphabet. Here N is length of string
A
and
M
is length of string
B
. Cases are separated by blank lines in input file.
Output
Output the case number and the expected answer for each test case.
Example
Input:
2
aabbaaccanbbbncc
abc
objectorientedprogramming
ii
Output:
Case 1: 6
Case 2: 15 | 33,961 |
Bubble Sort (BUBBLESORT)
One of the simplest sorting algorithms, the Bubble Sort, can be expressed as (0-based array):
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
Now, given an array of N integers, you have to find out how many swap opeartions occur if the Bubble Sort algorithm is used to sort the array.
Input
Input begins with a line containing an integer
T (1<=T<=100)
, denoting the number of test cases. Then T test cases follow. Each test case begins with a line containing an integer
N (1<=N<=10000)
, denoting the number of integers in the array, followed by a line containing
N
space separated 32-bit integers.
Output
For each test case, output a single line in the format
Case X: Y
, where
X
denotes the test case number and
Y
denotes the number of swap operations needed modulo 10000007.
Example
Input:
1
4
3 2 1 4
Output:
Case 1: 3 | 33,962 |
Ecstasy (NECSTASY)
Swapnil loves to ride swings at the local park, he feels ecstatic on riding one! However, the park plot is recently being used up for the construction of a public building. Swapnil had been depressed, until his mother decided to put up a swing right beside their home!
Swapnil’s mom Swagata is now faced with a new problem. She has decided on the position of the swing in her yard, but height of the swing needs critical calculation.
Swagata has picked point A (directly downward from the hanging point) in her yard such that A has a perpendicular distance of d meters from the foot of their house. His feet need clearance of x meters above the ground, and y meters away from the building. Swapnil can keep balance while riding the swing if the swinging angle does not exceed theta-degrees. Your task is to calculate the maximum height h of Swapnil’s swing.
Input
Input file contains multiple test cases. Each test case begins with a line containing three positive floating-point numbers-
d, x
and
y
(
0 < x, y < d < 100
) in meters. Next line of test case contains another floating point number, which is the maximum swinging angle theta in degrees (
0 < theta < 180
). It is guaranteed that all test cases will have a valid answer.
Output
For each sample input, output the maximum height h of the swing in meters with exactly two digits after decimal point.
Example
Input:
30.0 2.0 3.0
60.0
56.32 1.1 2.3
65.1
Output:
56.00
101.50 | 33,963 |
Laser Maze (LASER)
Standard mazes lose their mystery as one grows older. But throw in some lasers, and suddenly you've got yourself a recipe for cross-generational appeal. The object in any maze is to find your way from your starting point to some goal. In a
Laser Maze
you must additionally contend with laser turrets.
A laser turret is a stationary pillar that both blocks your movement and fires lasers from one side. Every time you take a step (either up, down, left, or right), every laser turret in the maze then rotates 90 degrees clockwise, and then shoots a momentary laser blast in the direction that it is facing. Needless to say, if you find yourself in the path of one of these lasers, you won't be around long enough to find a way out. A wall is a stationary pillar that blocks your movement, but does not fire lasers.
Lasers are powerful, but they do not pass through walls or laser turrets. The laser turrets respond to your movements, so you can't stand still and wait for the turrets to turn. If you reach the goal, but are immediately shot by a laser, your efforts will have been in vain, so make sure you reach the goal safely.
Input
Input begins with an integer
T
, the number of mazes you'll explore. For each maze, there is first a line containing two integers,
M
and
N
, the height and width of the maze, respectively. The next
M
lines contain
N
characters each, describing the maze:
. (empty space)
# (wall)
S (starting position)
G (goal)
< > ^ v (laser turrets)
The four symbols for laser turrets signify turrets that are initially pointing left, right, up, or down respectively before you take your first step.
Output
For the
i
th maze, print a line containing "Case #
i
: " followed by the smallest number of steps necessary to get to the exit without being hit by a laser, or the string "impossible'' if there is no way to reach the goal safely.
Constraints
1 ≤
T
≤ 100
1 ≤
M
,
N
≤ 100
Each maze will contain exactly one 'S' and exactly one 'G'.
Example
Input:
5
2 5
##^##
S...G
2 5
##v##
S...G
1 5
S..G<
1 6
S...G<
5 5
S....
.....
.>v..
.^<..
....G
Output:
Case #1: 6
Case #2: 4
Case #3: 3
Case #4: impossible
Case #5: 8 | 33,964 |
Help BTW (HELPBTW)
BTW wants to buy a gift for her BF and plans to buy an integer array. Generally Integer arrays are costly and hence bought the cheapest one from the market. Her BF is very judgmental and assess the quality of the array by just looking at the
smallest element
in the array. Hence, she decided to improve the quality of the array. Increment operation on array elements are very costly and would take
ONE FULL DAY
to complete. Also, Increment operations can be done in parallel on
at most M consecutive
array elements. She only has
K
days left. Help BTW calculate the
maximum possible “quality”
of the array she can attain.
(BTW BTW is the name of the character :P )
Input
Very first line contains T – (number of test cases)
First line in each test case contains N – (size of the array BTW has bought from the market), M, K (days left)
Second line in each test case contains N integers (values of the initial array BTW bought from the market)
Output
Print the maximum possible “quality” she can attain.
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ 10
5
0 ≤ M ≤ N
0 ≤ K ≤ 10
9
0 ≤ Values of array ≤ 10
9
Example
Input:
2
3 2 1
2 2 3
3 2 1
2 3 2
Output:
3
2 | 33,965 |
Divisibility Test (MATNUM)
Problem statement is simple and straight forward. You will be given a non-negative integer
P
of length
N
and you need to check whether it's divisible by
Q
?
Integer
P
will be given in its decimal representation with
P
0
as leftmost digit and
P
1
as second digit from left!
Rest of the digit can be generated from the formula:
P
i
= (4*P
i-1
+ P
i-2
) modulo Q
for
2 <= i <= N-1
Input
The first line contains one integer
T
- denoting the number of test cases.
T
lines follow each containing four integers
P
0
,
P
1
,
Q
and
N
!
Output
For each testcase output
YES
if the corresponding integer is divisible by
Q
and
NO
otherwise.
Constraints
T <= 100000
0 < P
0
, P
1
, Q < 10
0 < N <= 10
18
Example
Input:
4
1 4 2 2
1 4 2 1
4 2 3 2
3 4 7 3
Output:
YES
NO
YES
NO
Explanation
Value of
P
is
14, 1, 42, 345
in respective cases ! | 33,966 |
NEKAMELEONI (NEKAMELEONI)
"Hey! I have an awesome task with chameleons, 5
th
task for Saturday’s competition."
"Go ahead..."
(...)
“That’s too difficult, I have an easier one, they won’t even solve that one.”
“You are given an array of N integers from the interval [1, K]. You need to process M queries. The first
type of query requires you to change a number in the array to a different value, and the second type of
query requires you to determine the length of the shortest contiguous subarray of the current array that
contains all numbers from 1 to K.”
“Hm, I can do it in O(N
6
). What’s the limit for N?”
Input
The first line of input contains the integers N, K and M (1 <= N, M <= 100 000, 1 <= K <= 50). The
second line of input contains N integers separated by space, the integers from the array. After that,
M queries follow, each in one of the following two forms:
“1 p v” - change the value of the p
th
number into v (1 <= p <= N, 1 <= v <= K)
“2” - what is the length of the shortest contiguous subarray of the array containing all the integers from 1 to K
Output
The output must consist of the answers to the queries of the second type, each in its own line.
If the required subarray doesn’t exist, output −1.
Example
Input:
4 3 5
2 3 1 2
2
1 3 3
2
1 1 1
2
Output:
3
-1
4 | 33,967 |
DOMINO (DOMINO8)
Mirko received an N × N table for his birthday, where a non-negative integer is written in each field
of the table. Unfortunately, the written numbers are too large for Mirko’s taste, so he will place K
dominoes on top of the table that will cover the fields that are too large.
More precisely, Mirko places the dominoes according to the following rules:
each domino covers two fields of the table that are adjacent in a row or in a column,
the dominoes do not overlap (but can touch),
the sum of all visible (uncovered) fields needs to be as small as possible.
It is your task to determine the required minimal sum of visible fields. The test data will be such that
it will always be possible to place K dominoes without overlapping.
Input
The first line of input contains the integers N (1 ≤ N ≤ 2000), the dimensions of the table, and K
(1 ≤ K ≤ 8), the number of dominoes. Each of the following N lines contains N integers from
the interval [0, 1000]. These N × N numbers describe Mirko’s table.
Output
The first and only line of output must contain the minimal sum of visible fields after covering the
table with dominoes.
Example
Input:
3 1
2 7 6
9 5 1
4 3 8
Output:
31
Input:
4 2
1 2 4 0
4 0 5 4
0 3 5 1
1 0 4 1
Output:
17
Clarification of the first example:
We place the domino so it covers fields with numbers 9 and 5.
Clarification of the second example:
We place the dominoes so they cover fields [4, 5] and [5, 4] in the third column. | 33,968 |
Find the max XOR value (MAXXOR)
You have two integers
L and R
, and you are required to find the maximum xor value of a and b where L ≤ a ≤ R and L ≤ b ≤ R.
Input
Two integers in a line. L, R ≤ 10
9
.
Output
One integer, the answer.
Example
Input:
1 10
Output:
15 | 33,969 |
Palindrome Or Not (PLNDROME)
It's English class now. So John is bored as usual. To get over his boredom he is doing a very strange thing. He writes an arbitrary string on his notebook and then keeps changing a single character of the string every time and tries to find out if the string has become a palindrome.
As John is very smart this task is very simple for him.
But how simple is it for you? Can you be as smart as the great John?
You'll have to write a code that solves the similar problem and hopefully, as fast as John.
Input
First line of the input will be an integer T (T <= 15) denoting number of test cases.
Each test case starts with an integer N (1 <= N <= 100000) denoting the length of the string.
Next line will contain the string consisting of only small letters of English alphabet (a, b, c, ... x, y, z).
Then there will be another integer M (1 <= M <= 10000) denoting number of queries.
Each query will be in the form: i x, where i will be an integer (1 <= i <= N) and x will be a character, (a <= x <= z) and it will mean that the i-th character of the string has been changed to x.
Output
First you will have to print the test case number.
Then for each query in the test case you will have to print "YES" if the given string has become a palindrome. Otherwise print "NO" (without the quotes.)
See sample input/output and explanation for details.
Sample
Input
1
11
madamimadam
6
6 z
1 a
11 b
5 z
1 b
7 z
Input
Case 1:
YES
NO
NO
NO
NO
YES
Explanation:
After the 1st query the string is: madamzmadam, which is a palindrome
After the 2nd query the string is: aadamzmadam, which is
NOT
a palindrome
After the 3rd query the string is: aadamzmadab, which is
NOT
a palindrome
After the 4th query the string is: aadazzmadab, which is
NOT
a palindrome
After the 5th query the string is: badazzmadab, which is
NOT
a palindrome
After the 6th query the string is: badazzzadab, which is a palindrome | 33,970 |
Divisor Game (SIMPGAME)
Alice and Bob are playing a game. There are n piles having stones. In one move, either player can choose a pile and replace it by two piles, both of which have number of stones more than one and less than the number of stones in the original pile. Moreover, the sizes of both the new piles should be divisors of the size of the original pile. Alice and bob alternate turns and Alice always goes first. The player unable to make a move loses. Assume that both the players play optimally.
Input
The first line contains the number of test cases t.
For each test case, the first line contains the number of piles n.
The next line contain n space separated integers, the sizes of the piles.
Output
For each test case, output the name of the winner in a new line.
Constraints
1 ≤ t ≤ 100
1 ≤ n ≤ 1000
1 ≤ size of piles ≤ 100000
Example
Input:
3
1
5
2
3 9
4
4 6 9 10
Output:
Bob
Alice
Bob
Explanation
For the first case, Alice can't replace the pile, so Bob wins.
For the second case, Alice can replace the second pile from 9 to 3, 3. Now Bob can't replace any of the piles, so Alice wins. | 33,971 |
Divisible Fibonacci Numbers (DIVFIBS)
In mathematics, the Fibonacci sequence is calculated by adding the previous two members of the sequence. The first few Fibonacci numbers are
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Considering the indices start from 1 the 6
th
Fibonacci number in this sequence is 8 and is divisible by 1, 2, 4 and 8. You are given two indices L and R (L ≤ R) of this sequence and you have to calculate how many Fibonacci numbers are divisible by M in range [L, R] inclusive.
Input
Input begins with a line containing a single integer
T (1 ≤ T ≤ 500)
, denoting the number of test cases.
T
test cases follow. Each test case begins with a line containing three integers
L R (1 ≤ L ≤ R ≤ 100000)
and
M (1 ≤ M ≤ 10
18
)
.
Output
For each test case, output a single line containing the answer as an integer.
Example
Input:
3
6 6 4
4 18 5
1 10 3
Output:
1
3
2 | 33,972 |
Drawing Lines (DRWLNS)
John is a bit upset now. Today was his chemistry central viva and it did not go very well. So to cheer up he bought a notebook, a pencil and an eraser.
In the note book there are N points drawn in a row. The points are numbered from 1 to N serially.
Now, John decided to do a strange thing with those points.
At each moment, John puts his pencil or eraser at a point A and drags it to point B. As a result, some line segments may be created.
And then, sometimes he stops and thinks of a point C and tries to find out if point C is on a line segment or not.
You have to solve a similar problem.
Input
First line of the input will contain two integers N (1 <= n <= 10
9
) and M (1 <= M <= 10
5
) where N denotes number of points and M denotes number of queries.
Then M line follows. Each line contains a query.
Each query will be one of the following forms:
0 A B
: which means an eraser has been dragged from point A to point B.
1 A B:
which means a pencil has been dragged from point A to point B.
2 C:
which means you are asked to answer the state of point C. There will be at least one query of this type.
(It is guaranteed that A <= B and 1 <= A, B, C <= N)
Output
For each query of the form "
2 C
", print a single line. If point C is
NOT
on any line segment then print -1.
Otherwise, print the start and end point of the segment.
See sample and explanation for details.
Sample>
Input
25 14
2 10
1 20 25
1 9 13
2 12
2 7
1 11 21
2 15
0 17 20
0 22 25
2 21
2 5
1 1 8
2 12
2 4
Output
-1
9 13
-1
9 25
21 21
-1
9 16
1 8
Explanation
In the 1
st
query, there are no line segments. So point 10 is not on any segment.
After 2
nd
query, there is 1 line segment: [20, 25].
After 3rd query, there are 2 line segments: [9, 13], [20, 25].
In the 4
th
query, point 12 is on [9, 13] segment.
In the 5
th
query, point 7 is not on any segment.
After 6
th
query, there is 1 line segment [9, 25]. ([9, 13], [11, 21] and [20, 25] segments will merge into only 1 segment).
In the 7
th
query, point 15 is on [9, 25] segment.
After 9
th
query there are 2 segments: [9, 16] and [21, 21].
In the 10
th
query, point 21 is on [21, 21] segment.
In the 11
th
query, point 5 is not on any segment.
After 12
th
query there are 3 segments: [1,8],[9, 16] and [21, 21].
In the 13
th
query, point 13 is on [9, 16] segment.
In the 14
th
query, point 4 is on [1, 8] segment. | 33,973 |
Peculiar Number (PCLNMBR)
Ajoy has got some spare time today. He is using this spare time to think of a particular kind of number.
He calls it a ‘Peculiar Number’.
A peculiar number is define by three integers A, B and C and has the following characteristics:
If a number is a multiple of A but not a multiple of B then it is a peculiar number.
If a number is a multiple of both A and B then it will be a peculiar number only if it is also a multiple of number C. Otherwise it is not a peculiar number.
Now, Ajoy is trying to find the Nth peculiar number for a fixed A, B and C.
But Ajoy does not have all day. So he needs your help to solve the problem.
Input
First line of the input contains four integers A, B, C and M where (1 ≤ A, B, C ≤ 10
3
) and (1 ≤ M ≤ 10
5
) constraints hold.
M denotes the number of queries.
Each of the next M line contains an integer N (1 ≤ N ≤ 10
9
).
Output
For each query, print the Nth peculiar number.
Example
Input #1
3 2 4 3
1
2
3
Output #1
3
9
12
Input #2
983 991 997 3
323233123
2131234
1000000000
Output #2
318058785019
2097116472
983991931538
(set by: Nashir Ahmed) | 33,974 |
Palindrome in a Tree (PLNDTREE)
John has got a tree with N vertices. The vertices are numbered from 1 to N. He considers vertex 1 as the root of the tree. Each vertex of the tree contains a character C.
Now John is doing a weird experiment with this tree.
He often changes the character of a node in the tree and then sometimes he randomly selects a node v and tries to form a palindrome with all the characters in the subtree of node v.
But since John is very busy man and has a lot of other important experiments to do he needs your help on this one.
Input
First line of the input contains an integer N (1 ≤ N ≤ 100000) denoting the number of vertices.
Next N-1 lines contains two integers A and B (1 ≤ A, B ≤ N) which means there is an edge between vertex A and B.
Next line contains a string of length N. The i
th
character of this string denotes the character in node i.
Then there will be an integer M (1 ≤ M ≤ 100000) in a separate line denoting the number of queries. Next M lines will contain a query.
Each query will be in one of the following form:
0 x C
: which means the character of node x has been changed to C.
1 x
: which means you are asked to answer if a palindrome can be formed with all the characters in the sub tree of node x. There will be at least one query of this type.
Output
For each query of the form
“1 x”
print “YES” if a palindrome can be formed with all the characters in subtree of node x. Otherwise print “NO” (without the quotes).
All the characters in the input will be small letters of English alphabet, i.e. a, b, c ... x, y, z.
See sample input / output for details.
Sample
Input
7
5 4
1 5
6 3
1 7
5 6
6 2
abdaabc
7
1 1
1 5
1 3
0 7 a
1 1
0 4 z
1 5
output
NO
YES
YES
YES
NO
Explanation
In the 2
nd
query, the formed palindrome can be “badab” or “abdba”.
In the 3
rd
query, there is only 1 character “d”, which is a palindrome. | 33,975 |
Longest Perfect Increasing Subsequence (LPIS)
Dhrubo has a sequence of N integers. He is trying to find the longest perfect increasing subsequence of that sequence. But he is not very expert in finding longest perfect increasing subsequences. So he needs your help.
A subsequence is a sequence that can be derived by another sequence by deleting elements without changing the order of the remaining elements. An increasing subsequence of a sequence is a subsequence where the elements are sorted in increasing order.
Difference between an increasing subsequence and a perfect increasing subsequence is that in a perfect increasing subsequence the difference between any two consecutive elements is always 1.
For example, let’s consider a sequence S= {5, 2, 6, 3, 7, 8, 4}
{5, 3, 4} is subsequence of sequence S but not an increasing subsequence.
{5, 7, 8} is an increasing subsequence of sequence S, but not a perfect increasing subsequence.
But {5, 6, 7, 8} is perfect increasing subsequence as the difference between any two consecutive elements is exactly 1.
Note that, a single element will always be perfect increasing subsequence. So {5}, {2}, {7} are also perfect increasing subsequence of S.
Input
First line of the input contains an integer N (1 <= N <= 10
5
) denoting the length of the sequence.
Next line contains N integers separated by space which is the sequence. These integers will be greater than 0 and will not be greater than 10
6
.
Output
A single integer in a line denoting the length of the longest perfect increasing subsequence.
Example
Input #1:
9
5 1 5 6 2 3 8 7 4
Output #1:
4
Input #2:
8
2 2 1 3 5 4 5 6
Output #2:
5
(set by : Nashir Ahmed) | 33,976 |
Cricket Selection (CRICKDP)
Swagger loves playing cricket and its his childhood dream to represent his country at international level. A cricket tournament is being organised by BCCI to select few young talents in country. He played
N
matches and he was rated by selectors and public on basis of his performance in each match. Rating for his performances are given below in
1
indexed array
A
where
A
i
is his rating in
i
th
match.
His performance in some of the matches were extraordinary but unfortunately, some were total failure. Now swagger has a chance to improve his total rating which is sum of ratings in each of the matches. As he knows some of
M
judges, he tried to bribe them and finally they agreed to remove the rating of few matches where they were in charge. The
i
th
judge demanded
C
i
amount of money for removing each match of swagger's choice in the range
L
i
to
R
i
(both inclusive). Ratings of removed match will not be used in calculating total rating.
Now the real problem begins, he only has
K
amount of money and he wants to increase his total rating as high as possible. He is your friend and he also knows that you are a genius. Help him maximise his rating within the budget constraint.
That's a simple task for you, isn't it?
Input
First line contains number of test cases
T
.
First line of each test case contains
3
space separated integer
N, K, M
denoting Number of matches he played, amount of money he has and number of judges he can bribe.
Next line contains
N
space separated integers where
i
th
integer denotes rating of
i
th
match.
Next
M
lines of each test case contains three integers:
L, R
and
C
where the integers in the
i
th
line denotes value
L
i
,
R
i
,
C
i
respectively.
Output
For each test case, print a single integer which is maximum possible sum in a new line.
Example
Input:
2
5 7 5
5 -4 3 -3 3
1 1 5
1 3 2
2 4 5
1 5 7
3 3 2
5 10 2
-1 -2 -3 -4 -5
1 3 3
3 4 4
Output:
11
-6
Constraints
0 <
T
< 11
0 <
N, M
< 10
4
0 <
K
< 501
0 <
C
i
< 201
|A
i
|
<= 10
9 | 33,977 |
Ball sum (BALLSUM)
You have a bag filled with N balls. Each ball has a distinct number from 1 to N printed on it. All the numbers are distinct.
You withdraw two balls from the bag and take their sum.
You need to calculate the probability that the sum is not greater than the given number K (<= N).
The answer should be displayed in the form of p/q (except when the answer is 0 or 1.)
Input
Input consists of various test cases.
Each test case consist of two integer inputs, N and K.
(0 <= K <= N <= 1000000000)
The program stops taking input when N and K equals -1.
Output
Output the result in the form of p/q (except when the answer is 0 or 1.)
Example
Input:
3 2
100 5
10 6
-1 -1
Output:
0
2/2475
2/15 | 33,978 |
Next Lexicographically Greater Substring (NEXTLEX)
Consider a string
S
, consisting of only lowercase letters.
You are given a list of queries, each containing a non-empty string
STR
.
For each query, you have to output:
Among all substrings of S, the next lexicographically greater substring after STR.
Note: If no such substring of S exists which is lexicographically greater than STR, output -1.
Constraints
1<=|S|<=10^5
1<= Q <=10^5
1<=|STR|<=10^5
summation of |STR| for all Q <=10^5
Input
First line contains the string
S
.
The next line contains
Q
, the number of queries to answer.
The next Q lines contain
STR
for each query.
Output
Output the answer for each query in a new line.
Example
Input:
dabab
3
ab
abaa
bab
Output:
aba
abab
d
Input:
a
1
a
Output:
-1 | 33,979 |
Cat and Mouse I (CATMO1)
A cat is chasing a mouse in a rectangular room which contains some obstacles. The cat and mouse move according to the following rules:
The cat and mouse move in turns, in alternating fashion. The cat starts.
Both the cat and the mouse can only move to a location that does not contain an obstacle, and that is horizontally, vertically, or diagonally adjacent to their current location. Staying in the same location is always a valid move.
Neither the cat nor the mouse can move beyond the border of the room.
The cat is always aware of the location of the mouse, and vice versa.
Given the description of the room, and the starting positions of the cat and of the mouse, your task is to decide whether the mouse can avoid the cat forever or not.
Input
The first line of the input contains
T
(
1 ≤ T ≤ 10
), the number of test cases. Then
T
test cases follow, separated by blank lines. Each test case consists of a line describing the length of the two sides of the room,
R
and
C
(
1 ≤ R ≤ 10
,
1 ≤ C ≤ 10
), followed by a description of the room. The room is given as a matrix of
R
rows and
C
columns, where each entry of the matrix is either:
a dot (
.
), if the corresponding location is free of obstacles,
a hash sign (
#
), if the corresponding location contains an obstacle,
an
m
, if the corresponding location is the starting position of the mouse,
a
c
, if the corresponding location is the starting position of the cat.
The starting position of the cat and the starting position of the mouse are always different. Clearly, the starting positions are free of obstacles.
Output
The output consists of one line for each test case, containing the string
mouse
if the mouse can avoid the cat forever, and the string
cat
otherwise.
Example
Input:
2
3 3
#c#
.#m
#.#
3 3
#c#
.#.
#m#
Output:
cat
mouse | 33,980 |
Essay (ESSY)
The impending doom called final examination is approaching this year’s high school seniors: one of the compulsory tasks is going to be writing an essay in their mother tongue. Mirko is under the impression that certain political parties are going to keep their promises, those regarding informatization and digitalization, which is why he thinks that this year’s essays are going to be marked by a computer, instead of a human.
To test his doubts, Mirko is going to write an essay that doesn’t necessarily make sense at all, but should pass the automatic basic conditions check. The essay passes the check if:
it contains at least A, and at most B words;
every word contains at least one, and at most 15 letters;
the used vocabulary is large enough, in other words, the essay contains at least
B
⁄
2
different
words.
Mirko was up late last night watching Big Brother, so he is asking you to write such an essay instead of him. The essay should be output in a single line, using only lowercase letters of the English alphabet and spaces (therefore, without punctuation such as dots, commas and such). The words used can, but need not be, words from the English (or any) language.
Input
The first and only line of input contains the integers A and B (1 ≤ A ≤ B ≤ 100 000) from the task.
Output
The first and only line of output must contain any essay that meets the rules from the task.
Sample Tests
Please note: each of the lower outputs is written in one line, but is broken into several lines because of the lack of space.
Input 1
2 7
Output 1
this shakespeare fella is good
Input 2
26 30
Output 2
the teacher told us that we did not need to read that but it was too loud to hear so can i still get points for this
Input 3
19 19
Output 3
the consequences of the conceptual discourse in the aforementioned novella seemingly reflect the paradigmatic tendencies of the stylistical classification | 33,981 |
Social Network Community (SOCNETC)
Your friend came up with an idea of starting a social network-SOCNET.
Since, he is not as good a programmer as you are he needs your help to build certain features.
You need to build an ADD friend feature. if 'x' sends a friend request to 'y', he may accept it or deny it.
SOCNET has a special feature called 'community'. When two people 'x' and 'y' becomes friends, the communities of two are merged together. (If 'x' has no friends, it's community consist of only himself, size-1)
Since, your friend is low on funds, the data center he uses has a restriction-the MAXIMUM size of any community cannot exceed 'm'.
You need to work on following three types of queries-
A x y - x sends a friend request to y
E x y - check whether x and y are present in same community (print 'Yes' or 'No')
S x - prints the size of the community 'x' belongs to.
NOTE- A friend requested is accepted only if the merger of the two communities results in a community not greater than 'm'.
Input
The first line of input consists of two positive integers - n and m(n is the number of registered users and m is the maximum size of any community).
Next line consist of a positive integer q (number of queries).
q lines follows (Each line consist of a query as described in the problem statement).
The queries follows 1-indexing.
Constraints
1<=n, m<=100000,
1<=q<=200000
Output
For each query of Type - 'E', output in a single line-'Yes' or 'No'.
For each query of Type - 'S', output the size of the community to which 'x' belongs.
For further clarification, read the example given.
Example
Input:
5 3
8
S 2
A 2 3
E 2 3
S 2
A 4 5
A 3 5
E 3 5
S 3
Output:
1
Yes
2
No
2
Explanation
Initially no one has any friend. So community of '2' consist of only '2' i.e. size-1. Then '2' and '3' becomes friends .This forms a community of 2 people. '4' and '5' also becomes friends. This forms another community of 2 people. '5' is unable to accept friend request of '3' (because it would result in a community of 4 people(>3). | 33,982 |
Matrix (GSMATRIX)
Mr. Ganesh, a friend of Mr. Dengklek, give Mr. Dengklek a big matrix A dan asking the result of A
N
. Because the matrix A is too big and Mr Dengklek doesn't have a lot of time, he wants to minimize the number of multiplication needed for computing A
N
. In this case, assume Mr. Dengklek always stores the matrices that Mr. Dengklek ever computed, thus, if anytime Mr. Dengklek wants to use that matrix again, he can just directly use it without recomputing it.
You must help Mr. Dengklek to find out the minimum number of multiplication required to compute A
N
.
Input
The first line consist of a single integer N (1 ≤ N ≤ 120).
Output
In the first line, output the result asked in the problem statement above.
Example Explanation
Here is one of the possible minimum calculation to get A
15
.
Matrices that Mr. Dengklek have : A
1st multiplication : A × A = A
2
Matrices that Mr. Dengklek have : A, A
2
2nd multiplication : A × A
2
= A
3
Matrices that Mr. Dengklek have : A, A
2
, A
3
3rd multiplication : A
3
× A
3
= A
6
Matrices that Mr. Dengklek have : A, A
2
, A
3
, A
6
4th multiplication : A
6
× A
6
= A
12
Matrices that Mr. Dengklek have : A, A
2
, A
3
, A
6
, A
12
5th multiplication : A
12
× A
3
= A
15
Example
Input:
15
Output:
5 | 33,983 |
GCD OF MATRIX (GCDMAT)
You have given a matrix of size n×m. Every cell of matrix denote gcd of respective indices. For example
A 3×2 matrix have entries
gcd(1,1)
gcd(1,2)
gcd(2,1)
gcd(2,2)
gcd(3,1)
gcd(3,2)
You have given queries i1 j1 i2 j2.
You have to find the sum of matrix formed by upper left corner (i1, j1) and lower right corner (i2, j2).
Input
First line indicates number of test cases. (T<=500)
Next line have space separated two integers n and m. (1<=n, m<=50000).
Next T lines contains queries i1 j1 i2 j2.
where i1<=i2, j1<=j2.
Output
Print answer modulo M for each query in new line. (M=10^9+7)
Example
Input:
2
3 2
1 1 2 2
2 1 3 2
Output:
5
5 | 33,984 |
GCD OF MATRIX (hard) (GCDMAT2)
You have given a matrix of size nxm. Every cell of matrix denote gcd of respective indices. For example
A 3x2 matrix have entries
gcd(1,1)
gcd(1,2)
gcd(2,1)
gcd(2,2)
gcd(3,1)
gcd(3,2)
You have given queries i1 j1 i2 j2.
You have to find the sum of matrix formed by upper left corner (i1, j1) and lower right corner (i2, j2).
Input
First line indicates number of testcases. (T <= 50000)
Next line have space separated two integer n and m. (1 <= n, m <= 1000000).
Next T lines contains queries i1 j1 i2 j2.
where i1<=i2 j1<=j2.
Output
Print answer modulo M for each query in newline. (M=10^9+7)
Example
Input:
2
3 2
1 1 2 2
2 1 3 2
Output:
5
5 | 33,985 |
BMW (MARYBMW)
Mary is very very happy. You would be happy too if your parents give you the latest model BMW for your birthday. She wants to try out her new car and that's why she is going to visit her grandma.
There is a graph with N vertices representing N cities and M edges representing bidirectional roads between some pairs of cities. We can assume that Mary lives in city 1 and her grandma lives in city N. Unfortunately, not everything is so good in life and examples are the speed limits. Mary decided to drive with permanent speed. Each of these M roads has a maximum permissible speed V that Mary can't exceed. Well, her whims don't end here. As a lover of the extreme experiences she wants to drive her expensive car as fast as possible.
You are to write a program to find the maximum speed that Mary can reach her grandma's city without having arguments with the policemen (for their own good).
Note: There may be more than one road between two cities.
Input
The first line of the input contains the number of tests – T (T ≤ 5). On the first line of each test case there are two integers – N (2 ≤ N ≤ 50000) and M (1 ≤ M ≤ 100000). On the next M lines there are three integers A, B, and V representing a bidirectional road between cities A and B with speed limit V where 1 ≤ V ≤ 10
18
(It's a BMW after all).
Output
On a single line print the maximum possible speed Mary can reach. If she can't reach her grandma's house, print -1.
Example
Input:
1
4 5
1 2 80
3 1 20
2 3 60
4 3 300
2 4 90
Output:
80 | 33,986 |
Counting Divisors (DIVCNT1)
Let $\sigma_0(n)$ be the number of positive divisors of $n$.
For example, $\sigma_0(1) = 1$, $\sigma_0(2) = 2$ and $\sigma_0(6) = 4$.
Let $$S_1(n) = \sum _{i=1}^n \sigma_0(i).$$
Given $N$, find $S_1(N)$.
Input
First line contains $T$ ($1 \le T \le 100000$), the number of test cases.
Each of the next $T$ lines contains a single integer $N$. ($1 \le N < 2^{63}$)
Output
For each number $N$, output a single line containing $S_1(N)$.
Example
Input
5
1
2
3
10
100
Output
1
3
5
27
482
Explanation for Input
- $S_1(3) = \sigma_0(1) + \sigma_0(2) + \sigma_0(3) = 1 + 2 + 2 = 5$
Information
There are 6 input files.
- Input #1: $1 \le N \le 100000$, TL = 2s.
- Input #2: $1 \le T \le 120,\ 1 \le N \le 10^{15}$, TL = 15s.
- Input #3: $1 \le T \le 60,\ 1 \le N \le 10^{16}$, TL = 15s.
- Input #4: $1 \le T \le 25,\ 1 \le N \le 10^{17}$, TL = 15s.
- Input #5: $1 \le T \le 10,\ 1 \le N \le 10^{18}$, TL = 15s.
- Input #6: $1 \le T \le 5,\ 1 \le N < 2^{63}$, TL = 15s.
My C++ solution runs in about 1.3 seconds for each input #2 - #6.
Note
Probably, $O(\sqrt{n})$ solutions will not pass.
Intended solutions have a running time of about $O(n^{1/3} \log n)$.
The answer can be $\ge 2^{64}$. | 33,987 |
Trending GCD (TRENDGCD)
Problem statement is simple. Given
A
and
B
you need to calculate
S(A, B)
.
Here,
f(n)=n, if n is square free otherwise 0
. Also
f(1)=1
.
Input
The first line contains one integer
T
- denoting the number of test cases.
T
lines follow each containing two integers
A, B
.
Output
For each testcase output the value of
S(A, B) mod 1000000007 in a single line
.
Constraints
T <= 1000
1 <= A, B <= 1000000
Example
Input:
3
42 18
35 1
20 25
Output:
306395
630
128819 | 33,988 |
Revenge of Arjuna (THEWAR)
The
Mahabharata
is an epic narrative of the
Kurukshetra War
and the fates of the Kaurava and the Pandava princes. Arjuna was the 3rd of the Pandava brothers. He is considered the protagonist of the Mahabharata with Krishna. Abhimanyu was the son of Arjuna and Subhadra. Abhimanyu's story came to prominence on the 13th day of the war when he entered the powerful Chakravyuha battle formation of the Kaurava army. Drona had designed this configuration in order to capture Yudhishthira. On the side of the Pandavas, only Krishna and Arjuna were aware of the secret technique to break this seven-tier, defensive, spiral formation.
Seeing Yudhishthira's panic, Abhimanyu revealed that while he didn't know how to exit the formation, he would be able to break into it. A plan was formulated that the Pandava forces would enter the Chakravyuha after Abhimanyu, and shatter it from within. But as soon as Abhimanyu entered the Chakravyuha, Jayadratha stopped the four Pandavas from entering it. At last Abhimanyu was killed inside the Chakravyuha. The news of Abhimanyu's death reached his father Arjuna at the end of the day. Arjuna vowed to kill Jayadratha the very next day by sunset, and failing to do so, would commit suicide by self-immolation immediately. So Arjuna has to reach Jayadratha before sunset.
There are
N
spots in the Kauravas army numbered from
0 to N-1
. Arjuna was always at spot
0
and Jayadratha was always at spot
1
. He need to reach the spot '
1
' as soon as possible killing the soldiers of the army. The time to reach each spot is given in the form of N x N array. Also Arjuna had '
K
' Divyastras (Divine arrow) which
halves the time
(only take half of what it normally would) to reach any spots. Arjuna was not allowed to use more than one Divyastras at same time. He may or may not use Divyastra. Find the smallest time in which Arjuna can reach Jayadratha.
Input
First line T the number of test cases. (T<=55)
Second line N the number of spots in the battle. (2<=N<=50)
Next N*N matrix indicates the time to reach other spots. (Each value in the matrix <=50)
K the number of Divyastras Arjuna had initially. (0<=K<=50)
Output
A Single value indicating the minimum time required to reach Jayadratha.
Example
Input:
1
3
0 9 4
9 0 4
4 4 0
1
Output:
4.5
Explanation
According to given data, you need:
9 units of time to move between spots 0 and 1.
4 units of time to move between spots 0 and 2.
4 units of time to move between spots 1 and 2.
You have a single Divyastra.
The optimal solution is to use a Divyastra and move directly from spot 0 to spot 1. This will take 9/2 = 4.5 units of time. | 33,989 |
Sum the Decimal-part II (SUMDEC2)
A much easier version of this problem can be found here-
SUMDEC1
. In case you haven't tried it out, try the first part.
In this problem, you are given a number. You need to output the sum of the first 1000 decimal places of the square-root of the number (ignore the integral part).
For example-if the given number is 2. The square-root of 2 is 1.4142135623..... So, ignore the number before decimal (1 in this case) and add the first 1000 digits after decimal and output them as result. (4482 in this case.
NOTE: If the number is a perfect square, the output should be 0.
Input
the first line of input consist of t (the number of test cases).
t lines follow-Each line consist of a non-negative integer n.
Output
Output in separate lines the result corresponding to integer n.
Constraints
1 ≤ t ≤ 100
1 ≤ n ≤ 100000
Example
Input:
2
4
2
Output:
0
4482 | 33,990 |
HARRY POTTER AND THE FORBIDDEN FOREST (HPFORF)
Voldemort is back and this time even more stronger. To stay immortal this time he has divided his soul into more than 7 parts (horcrux) and has hidden them in the Forbidden Forest.
Forbidden Forest is represented by a rectangular field of n x m cells. Each cell is either empty or has a tower. Empty cells are marked with ‘.’ and cells with tower are marked with ‘*’. Every pair of adjacent cells of different type (one empty and one having a tower) has a hole in the wall of the tower with one horcrux hidden.
As Harry Potter is the chosen one he has to weaken Voldemort as much as he can by finding maximum possible number of horcrux. Harry starts from an empty cell and can only move to those empty cells which share a common side with the current one. Harry can find those horcrux which is in a hole of the wall of the tower adjacent to the cell which Harry will visit.
Note: One tower can have more than one holes (and thus more than one horcrux), each in different walls having an adjacent empty cell.
For different starting positions you have to calculate how many horcrux Harry Potter can find.
Input
First line contains an integer t - number of test cases.
Each test case contains three integers n, m and k - dimension of the Forbidden Forest and the number of starting positions to process.
3 ≤ n, m ≤ 500
1 ≤ k ≤ min(n * m, 100000)
Each of the next n lines contains m symbols ‘.’ or ‘*’ - description of the Forbidden Forest. All the border cell are guaranteed to be ‘*’ so that Harry don’t go out of the Forest.
Each of the last k lines contains two integers x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) - the row and column of one of the starting position of Harry Potter respectively. Rows are numbered from top to bottom and columns from left to right. All starting positions are guaranteed to be empty cells.
Output
Print k integers (each in new line) - the maximum number of horcrux Harry Potter can find if he starts in the corresponding position.
Example
Input:
2
5 5 2
*****
*.*.*
***.*
*.*.*
*****
2 2
2 4
4 5 1
*****
*..**
**..*
*****
3 4
Output:
4
8
10 | 33,991 |
Windy Cannon (JC15A)
Windy Cannon
This day is very windy, the wind blow very fast that it may be faster than the speed of cannon ball. On this windy day, Gunawan want to test his new prototype cannon, he want to shoot the target at specific location. But before doing that, he wonder how long it take for the cannon ball to hit the target. He know percisely the position of his cannon, the location of the target, the speed of his cannon ball, the speed of wind blows, and the direction of the wind, but unfortunately he forgot to bring the calculator so he ask you for help to calculate the minimum time needed for the cannon ball to hit the target or specify if it's impossible. Can you help him? You can assume that the speed of cannon ball relative to the wind is constant, all other physical effect such as gravity, air friction, temperature, magnus effect are ignored.
Input
The first line there are 4 integers and 1 character CP, TP, CBS, WS, WD denoting cannon position (m), target position (m), cannon ball speed (m/s), wind speed (m/s), and wind direction respectively.
Output
Print how many seconds the minimum time needed for cannon ball to hit the target rounded to 6 digits after decimal point.
If it's impossible for the cannon ball to hit the target, print "Impossible" without quotes.
Constraint
0 ≤ CP ≤ 100
0 ≤ TP ≤ 100
0 ≤ CBS ≤ 100
0 ≤ WS ≤ 100
if WD = 'L', it means that the wind blow into negative direction (left in catesian plane).
if WD = 'R' it means that the wind blow into positive direction (right in cartesian plane).
Sample 1
Input
2 10 2 1 L
Output
8.000000
Sample 2
Input
2 10 2 1 R
Output
2.666667
Sample 3
Input
2 10 2 3 L
Output
Impossible
Sample 4
Input
10 2 2 3 L
Output
1.600000
Sample 5
Input
50 50 12 34 R
Output
0.000000
Sample 4 Explanation
The cannon ball move at speed 2 m/s relative to the wind, so if it shoot to the right, because of the wind blowing 3 m/s to the left relative to the ground, the cannon ball move (3-2=1) m/s to the left relative to the ground and will eventually hit the target in 8 seconds, but this is not optimal, it's faster to shoot the cannon ball to the left, because the wind blowing 3 m/s to the left relative to the ground (and the same direction as the cannon ball move relative to the wind), so the cannon ball will move (3+2=5) m/s to the left relative to the ground and will eventually hit the target at (10-2)/5 = 8/5 = 1.6 seconds. We need to print the result rounded to 6 digit after decimal places, so the minimum time needed for the cannon ball to reach the target is 1.600000 seconds. | 33,992 |
Folding Stick (JC15B)
Folding Stick
Today Satria really excited about fractals (recurrence pattern), the first fractal type he learn is the dragon curve fractal. To make the dragon curve, it can be easily simulated by folding the paper and open it 90 degrees (parellel to X axis or Y axis) like this image below:
Satria realized that the can be many ways to fold the paper, so he make an experiment. Initially there is a stick length 2
N
, he then place the stick parallel to x axis with one end lies on coordinate (0,0) and the other end lies on coordinate (2
N
,0). He then fold the stick, so the new folded stick occupy (0,0) to (2
N-1
,0) he keep doing that until the final folded stick occupy (0,0) to (1,0). In each foding there are two types of folding, folding UP (via possitive Y coordinate) and folding down (via negative Y coordinate). he then open all the folding with angle 90 degrees so each stick segment will be parallel ot X axis or Y axis. Now he wonder if he open all the folding with angle 90 degrees, what is the coordinate of the other end of that stick. Can you help him?
Input
The first line there is an integer N denoting number of folding and a string S the sequence of folding and the type of folding.
Output
You sould output two integers x and y which is the coordinate of the other end of that stick.
Constraint
1 ≤ N ≤ 50
Length of string S is equal to N, in other word: |S|=N.
String S containing two possible characters:
'U' means folding UP (positive Y direction)
'D' means folding DOWN (negative Y direction)
Sample 1
Input
1 U
Output
1 1
Sample 2
Input
1 D
Output
1 -1
Sample 3
Input
2 UD
Output
2 0
Sample 4
Input
2 DU
Output
2 0
Sample 5
Input
3 UUU
Output
-2 2
Sample 3 Explanation
Here is the image illustrating sample 3 on how the stick is folded and openned with 90 degrees angle.
As seen in the picture above the other end of the stick after folding and openning lies on coordinate (2,0).
Sample 5 explanation
Here is the final openned stick on test case 5, the other end of the stick after folding and openning lies on coordinate (-2,2) | 33,993 |
Walking Jumper (JC15C)
Gunawan really bored today, he sit in his home reading newspaper, but suddenly he found very interesting news. Using modern radar, Satria detect a new chemical stone on top of the nearby mountain, the stone is so rare so it will be very valuable. After Gunawan know that news, he decided to climb that mountain to collect some of that valuable stone. To climb the mountain he need energy, to use energy he need oxygen, he know that when climbing the mountain there are some part of the mountain containing sulphuric gas and it's toxic so decreasing his oxygen, fortunately some other mountain part containing clear breathable air that increasing his oxygen.
Because it's dangerous to climb the mountain without a map containing information about which part of the mountain has breathable air and which part of the mountain containing toxic sulphuric gas, Gunawan went to Tjandra house because Tjandra has that mountain map. Tjandra strongly advise Gunawan to take a deep breath before climbing this mountain to store some oxygen in his body and recommend him to train his jumping power to avoid the toxic gas part (by jumping of course).
After a few days of training, Gunawan observed that his optimal jumping power is proportional to the amount of oxygen inside his body, that means if he has K unit of oxygen inside his body he can jump at most K unit skipping K-1 area that may be containing toxic gas. Not only that, he also observed that after he jump his leg is shaking for a while so he must walk at some distance, this distance also the same as the distance he jumped, for example after he jump with distance K unit, he must walk K unit before he can make another jump. His last observation is that jumping has no effect with his oxygen inside his body, that means no matter how far he jump the amount of oxygen in his body remain the same.
Tjandra tell Gunawan that he must keep his oxygen level positive, if he run out of oxygen (oxygen level in his body < 1) he will die. So Tjandra want to give Gunawan some oxygen supply, Tjandra know that pure oxygen is expensive this day so he must give the minimum possible oxygen that is enough to bring Gunawan to top of that mountain, also he also want the instruction (jump or walk plan) for Gunawan to use that oxygen wisely so he can reach the top of the mountain without running out of oxygen.
The objective is to keep the Gunawan from running out of oxygen, not necessarily to maximize Gunawan's oxygen level at the top of the mountain. Tjandra know that you're very good at this kind of task so he call you using his old phone for your help. Can you help them?
Input
The first line there is an integer N denoting number of area in the map.
On the second line there is a string S of length N which is the content of that map.
Length of string S is equal to N, in other word: |S|=N
The first character of string S describing the area that is nearest to Gunawan's house, and the last character of string S describing the area that is nearest to the top of the mountain.
String S containing two possible characters:
'+' means that area is a breathable area that increase Gunawan's oxygen level inside his body by one unit.
'-' means that area is a toxic sulphuric gas that decrease Gunawan's oxygen level inside his body by one unit.
Output
On the first line you should output an integer that is the minimum number of oxygen that Gunawan needed at the beginning.
On the second line and after you should output one instruction for each line, there are two types on instruction:
If Gunawan need to walk to the next area, print a single character 'W' on that line
If Gunawan need to jump K unit (skipping K-1 area), print a single character 'J' and an integer K respectively on that line.
Constraints
1 ≤ N ≤ 1000
Examples
Input 1:
1
+
Output 1:
1
W
W
Input 2:
1
-
Output 2:
2
J 2
Input 3:
5
-----
Output 3:
4
J 4
W
W
Input 4:
5
++---
Output 4:
1
W
W
J 2
W
W
Input 5:
8
-+----+-
Output 5:
3
J 2
W
W
J 2
W
W
W
Sample 5 Explanation
If Gunawan has less than 3 unit of oxygen inside his body at the beginning, he can't make it to the top of mountain, so the minimum number of oxygen needed is 3.
Here is the explanation of move command:
[{3} G-+----+-_]
: Initially Gunawan has 3 unit of oxygen inside his body.
[{3} G-+----+-_] ="J 2"=> [{4} _-G----+-_]
: Gunawan jump 2 step forward to avoid the first toxic area, now he land on the breathable oxygen area increasing his oxygen level to 4.
[{4} _-G----+-_] =="W"==> [{3} _-.G---+-_]
: Because Gunawan's leg is shaking after jump, he is unable to jump so his only choice is to walk to next area decreasing his oxygen level to 3 because that next area is toxic.
[{3} _-.G---+-_] =="W"==> [{2} _-..G--+-_]
: Similar to his previous move, his only choice is to walk to the next area.
[{2} _-..G--+-_] ="J 2"=> [{1} _-...-G+-_]
: After walking two steps his leg become normal again so he can jump to avoid the next toxic area, but unfortunately his remaining oxygen is only 2 so the best jump he can do is to jump 2 step forward landing on toxic area decreasing his oxygen level to 1.
[{1} _-...-G+-_] =="W"==> [{2} _-...-.G-_]
: Fortunately the next area is breathable area, so he walk to this area increasing his oxygen level to 2.
[{1} _-...-.G-_] =="W"==> [{2} _-...-..G_]
: Because the effect of previous jump is not gone, his leg is still shaking and his only choice is to move to the next area decreasing his oxygen value to 1 again.
[{1} .-...-..G_] =="W"==> [{1} .-...-...G]
: Finally to reach the top of the mountain he need to walk once again and completed his mission
Don't worry about how Gunawan go home, because he is at the top of the tall mountain, to going home he simply jump of a cliff with his parachute :) | 33,994 |
Perfect Superstring (JC15D)
Perfect Superstring
Satria is a smart person, after he understand the system of binary digits he immediately write a new challenge! The challenge is, give him a binary string S he will tell you a binary string B which is not substring of S. Because Satria is smart, he will always tell buinary string B with minimum length. But everything has a limit, even Satria's intelligence, his brain will be tired if he check subtring of S of length more than N. So he can't tell the binary string B if the binary string S containing all the possible B of length ≤N, in orther word S is superstring of all possible binary string B of length ≤N, lets call S "Perfect Superstring" of order N if it meet this consition.
Gunawan know this challenge and Satria's intelligence limit want to make a binary string S which is perfect superstring of order N. Then he write down all possible binary string B, and concatenate them. For example if he want to make perfect superstring of order 2, he will write: {0,1,00,01,10,11} and concatenate to 0100011011 and submit it. Unfortunately Satria is so smart so his limit will be high. So the Gunawan method to generating perfect superstring of order high is inefficient, but Gunawan never give up, he insist to write his perfect superstring using his method.
After Gunawan writing K digits of his binary string, Tjandra who is curious about Gunawan's serous face ask him why he is so serious.
Tjandra said
: "What are you doing?"
Gunawan replied
: "I want to solve Satria's challange"
Tjandra replied
: "Sound interesting, can you explain the challenge?"
(Gunawan explaining Satria's challenge)
Tjandra said
: "wow, that's interesting, how do you solve this challenge?"
(Gunawan explaining his method)
Tjandra said
: "That's inefficient, it's enough to concatenate possible binary string B of length N, forget about binary string that has length less than N because all of them will eventually be substring of binary string which has large length, for example if you want to make perfect superstring of order 2 your string will be 0100011011, but it's enough to just concatenate {00,01,10,11} and become 00011011, it's shorter and it's perfect superstring of length 2!"
Gunawan replied
: "wow it's shorter! I never think about that, is that the minimum possible length"
Tjandra replied
: "No, there are the shorter one, for example in binary string 000110011 the substring 11 appear 2 times, so we can delete one digit of '1's and i't still meet the perfect superstring of order 2"
Gunawan replied
: "You're right, I don't like wasting my energy, I want the perfect superstring of order N with minimum possible length!"
Tjandra replied
: "Unfortunately no simple method for generating the minimum posible length of perfect superstring, but I know someone who can generate it for you with modern computer"
(Tjandra pulled his old phone from his pocket, getting ready to call you for help)
Gunawan said
: "Wait, I already write K binary digits, I don't want to delete them and start from the beginning"
Tjandra replied
: "What -_- Ok, I'll consider that"
Now Tjandra call you using his old phone for help, because he know you're skilled at string processing. Can you help them?
Input
The first line there is an integer N denoting the order of perfect superstring on Satria's challenge.
On the second line there are one integer K and one string X, K denoting the length of binary string that is already writen by Gunawan, and X is that binary string itself.
Output
The the first line you should output minimum possible length of {perfect superstring of order N starting with X of length K}, let's call this number L.
On the second line you should output a binary string of length L starting with K and it is perfect superstring of order N.
Constraint
1 ≤ N ≤ 20
0 ≤ K ≤ N
String X will have length K, in order word |X|=K.
It can be empty string if K=0
.
Sample 1
Input
1
1 0
Output
2
01
Sample 2
Input
1
1 1
Output
2
10
Sample 3
Input
2
2 01
Output
5
01100
Sample 4
Input
3
3 110
Output
10
1101000111
Sample 5
Input
3
3 110
Output
10
1100010111
Sample 4 (and 5) Explanation
In sample 4, string 1101000111 starting with string 110: [110]1000111, so Gunawan doesn't need to erase his already written number from the begining.
It also meet the perfect supertring of order 3 because all binary string of length ≤3 is substring of that string.
Here is the proof:
0: 11
0
1000111
1:
1
101000111
00: 1101
00
0111
01: 11
01
000111
10: 1
10
1000111
11:
11
01000111
000: 1101
000
111
001: 11010
001
11
010: 11
010
00111
011: 110100
011
1
100: 110
100
0111
101: 1
101
000111
110:
110
1000111
111: 1101000
111
Note that there can be multiple solution, the string 1100010111 as shown on sample 5 is another minimal length perfect superstring of of order 3 starting with 110. | 33,995 |
Laser Beam 2.0 (JC15E)
Laser Beam 2.0
Laser is a beam of light that can bounce if it hit a mirror, Satria who love beauty of nature make an experiment with grid of mirror and some laser, this is the second time Satria playing with laser, so he named his experiment "Laser Beam 2.0". The experiment is so great, many people like with Satria's experiment because that bouncing laser can make a beautiful pattern.
Gunawan who curious about beautiful pattern secretly experimenting with Satria's laser and mirror when Satria not home, but something terible happen, he accidentally crossed two different charged laser, so it break all the mirror and destroying Satria's experiment.
Fortunately, the blueprint of Satria's laser input/output is intact, but the blueprint of how the mirror is placed is burned so it's unreadable. Satria is sad, he should build the experiment from the beginning.
Tjandra who hear the tragedy come to Satria's house and know the condition. He suggest that no need for Satria to experiment from the beginning because the blueprint of Satria's laser input is intact.
Satria said
: "Is it possible to recover my experimet? The mirror blueprint is gone, even if we have the laser input/output, we don't know how to dirrect the input laser to output laser"
Tjandra replied
: "Maybe that's not true, it depend on how your blueprint is designed can I know more about your experiment and your blueprint?"
Satria replied
: "
My experiment consiting of 2D grid of mirror and an array of lasers on each side (there are 4 sides) and each laser is shoot to inside of the grid, there are two kind of mirror, diagonal up '/' and diagonal down '\', based on my observation, diagonal up '/' mirror will bounce the laser with this rule: {from left to up; from up to left; from right to down; and from down to right}, and diagonal down '\' mirror will bounce the laser with this rule: {from left to down; from down to left; from right to up; and from up to right}. The blueprint tells about how laser are connected, after bouncing so many times, eventually the laser will go outside the grid and hit another laser, in that phenomena I call that two laser is 'connected'. In the blueprint each number appear exactly 2 times that's mean the laser with the same number are 'connected' each other.
That's my experiment and how the input/output blueprint work. So, is it possible using input/output blueprint to re-create missing mirror blueprint?"
Tjandra replied
: "Yes, it's possible, but the result will probably be not the same as the old one because the mirror blueprint that satisfy your input/output blueprint is not unique"
Satria replied
: "That's okay, if it satisfy the input/output blueprint, It'll always be as beautiful as original one"
Tjandra replied
: "I'm glad to hear that. Okay, I know someone who is genious in programming, I'll call him to help you recover your experiment"
Now Tjandra call you using his old phone for help, because he believe that you're so promising to recover Satria's experiment. Can you help them?
Input
The first line there are two integers X and Y denoting number of rows and number of colums respectively of Satria's mirror grid.
On the second line there are Y integers denoting array of laser on top of that grid that is initially shoot in down direction.
Each of next X lines there are two integers A
i
and B
i
:
A
i
means i-th laser (counting from top to bottom) on left of that grid that is initially shoot in right direction.
B
i
means i-th laser (counting from top to bottom) on right of that grid that is initially shoot in left direction.
The last line there are Y integers denoting array of laser on bottom of that grid that is initially shoot in up direction.
Output
If it's impossible to re-create Satria's mirror blueprint, print "-1" without the quotes.
Otherwise print X rows and Y collums of mirror blueprint, character '\' ASCII(92) denoting diagonal down mirror, and character '/' denoting diagonal up mirror.
Constraint
1 ≤ X ≤ 100
1 ≤ Y ≤ 100
1 ≤ Each numbers that appears in the input (except X and Y) ≤ X+Y
Each numbers in the input (except X and Y) will appear excactly twice.
Sample 1
Input
1 1
1
1 2
2
Output
/
Sample 2
Input
1 1
1
2 1
2
Output
\
Sample 3
Input
3 1
1
1 3
2 2
3 4
4
Output
-1
Sample 4
Input
3 1
1
1 2
3 2
3 4
4
Output
/
\
/
Sample 5
Input
4 7
7 7 8 9 10 10 2
1 2
1 3
4 3
5 6
5 4 8 9 11 11 6
Output
\/\\\/\
////\//
/\\\\\\
/////\/
Sample 5 Explanation
If all pair of identical number on input is connected, then it'll satisfy Satria's input/output blueprint. Here is an image that show the correctness of sample 5 output. | 33,996 |
Colorful Beads (JC15F)
Colorful Beads
Yay, today is colorful day! why? because there are so many colorful beads on the table. Satria want to make a necklace using all that available beads, in order to make the necklace most valuable, Satria arrange the beads using magic secret formula. Gunawan secretly want to know Satria's secret formula, so he try all possible beads combination until the beads become most valuable, at first he easily found the most valuable beads combination for small number of beads, but he can't derive general formula, he keeps trying, and tying, and trying... Never give up!
Someday, Tjandra meet Gunawan and suggest him to not continuing his bruteforce action because the number of possible combinations are too many. Gunawan doesn't believe that and ask Tjandra to show him number of possible combinations.
Gunawan said
: "If I have this N beads how many combinations are there?"
Tjandra replied
: "It's N facorial combinations"
Gunawan replied
: "But that's not always true some of my beads has more than one color, so if I swap beads with same color doesn't change tha necklace value"
Tjandra replied
: "Okay, tell me the details of your beads"
Gunawan replied
: "My beads has M distinct colors, it has K
1
beads of color 1, K
2
beads of color 2, ... , K
M
beads of color M"
Tjandra replied
: "It will have F(K
1
+K
2
+...+K
M
)/(F(K
1
)*F(K
2
)*...*F(K
M
)) combinations where F(N) means N factorial"
(5 minutes later)
Gunawan said
: "Hey, your formula is not true, I tried it with 2 green beads and 2 blue beads, your formula showed F(2+2)/(F(2)*F(2)) = 24/(2*2) = 6 combinations, but actually it has only 2 combinations"
Tjandra confidently replied
: "I'm good at math, I'm sure my formula is correct"
Gunawan replied
: "I made these two different necklace: {1:{g,g,b,b},2:{g,b,g,b}} [g=green beads, b=blue beads] can you make the third necklace that is different than both of these?"
Tjandra replied
: "That's easy, here is the third necklace: {b,g,b,g} "
Gunawan replied after rotating that necklace
: "Look, your neclace become equal to my second necklace: {b,g,b,g} -> {g,b,g,b}"
Tjandra replied
: "Oops, I forgot about necklace rotation, you'really smart bruteforcer, why you don't believe me that number of combination is too many even though it's a little bit smaller than my calculation"
Gunawan replied
: "A little bit? do you think 6 and 2 is little difference?"
Tjandra replied
: "huh -_- I can show you that the exact number of distinct combinations, but unfortunately the formula become too complex and I don't bring a computer, is there any computer here?"
Gunawan replied
: "No, I'm also don't have a computer"
Now Tjandra call you using his old phone for help, because he know that now you're sitting in front of your computer. Can you help them?
Input
The first line there is an integer K denoting number of distinct beads colors.
On the second line there are K integers, K
i
is number of beads with i-th color.
Output
Print single integer that is the number of distinct color combination. Since this number is very large as Tjandra predict, output it modulo 10
9
+7.
Constraint
1 ≤ K ≤ 1000
1 ≤ K
i
≤ 1000
Sample 1
Input
1
1000
Output
1
Sample 2
Input
2
2 2
Output
2
Sample 3
Input
3
1 1 1
Output
2
Sample 4
Input
4
2 3 4 5
Output
180180
Sample 5
Input
5
1 2 3 4 5
Output
2522520
Sample 3 Explanation
On sample 3 there are 3 distinct color of beads, there is 1 bead for each color.
Let's assume those 3 distinct color are red, green, and blue,
here are 2 possible necklace, all other beads combination can be rotated to obtain one of thoose necklace below.
Note that if we can flip the necklace, both necklace are equal, but in this problem, we assume the front side of necklace is different than the back side, so both necklace above are considered different. | 33,997 |
Captain Claw (CLAW)
Captain Claw is at the bank of a river of acid and he needs to cross it. The river is x metres wide but Captain Claw can jump at most d metres.
However, the Captain can jump on stones which keep appearing in the stream.
Input
There are multiple test cases. For each test case.
The first line contains n, x and d.
The next n lines denotes subsequent seconds.
For each line, the first integer, c, denotes the number of number of stones appearing in this second.
Then c integers follow.
The ith integer means that a stone would appears at the position of that integer.
Find the minimum time needed by the Captain to cross the river.
1 ≤ t ≤ 30
1 ≤ x ≤ 10
5
1 ≤ d ≤ x
1 ≤ n ≤ 10
3
1 ≤ sum(c) ≤ 10
5
Assumption
Captain Claw is super fast. The time taken by jumps is negligible to a second.
Output
Print a single integer in each line - the time taken to cross the river.
Output -1 if its not possible to cross the river in n seconds.
Example
Input:
1
4 6 2
1 5
1 3
1 1
1 2
Output:
3
Explanation:
Sec 1: Captain Waits
Sec 2: Captain Waits
Sec 3: Captain Jumps from bank(0) → 1 → 3 → 5 → bank(6) | 33,998 |
Lost and survived (LOSTNSURVIVED)
On September 22,
2004, Oceanic Flight 815 crashed on a mysterious island somewhere in the pacific.
There actually were survivors in the crash, N survivors. The mysterious island kept on moving in space - time, so no rescue reached them.
Initially every survivor was on his own. But soon they realized there are these “The Others” (Scientists of damn Dharma Initiative) on this Island too.
So to protect themselves from mad Scientists they started uniting into groups after Dr. Shephard said “Live together or die alone”.
You have to handle Q queries; which consist of two survivors becoming friends and thereby uniting their respective groups into a larger group.
After each query, output the difference between the group of largest size and group of smallest size at that time.
If there is only one group, output 0. At first, everyone is in their own group.
Also note, if the two survivors in the query are already in the same group, print the current answer, and skip merging groups.
Also do comment if you have watched Lost :-p
Input
The first line consists of two space separated integers, N and Q
The next Q line consists of two integers, A and B, meaning that survivor A and survivor B became friends uniting there groups.
Output
Output Q lines, the answer after each query.
1 ≤ N ≤ 100000
1 ≤ Q ≤ 100000
Example
Input:
5 3
1 2
2 3
5 4
Output:
1
2
1 | 33,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.