task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
The wit of Tenali Raman (TENALI)
Tenali Ramakrishna, who was known as Vikatakavi (jester poet) was a Telugu poet generally known for his wit and humor. He joined the famous troupe of 'Bhagavatha Mela'. When the troupe came to Vijayanagara to perform in front of the king, Ramakrishna's performance caught the eye of the King Krishnadevaraya and other people. He shared his life story with Krishnadevaraya, who granted him the post of the comic poet in the court. Ramakrishna attained fame as a great jester poet. Tenali was instrumental in protecting the King many times, coming to his rescue in critical situations. So Krishnadevaraya praised Tenali very much and this made other ministers jealous of him. One of the minister decided to insult Tenali in front of the king.
The minister then took a bag containing
N
number of gems numbered from
0 to N-1
.He picked some
K
of the gems and asked the soldiers to distribute it to the people. The minister computed the sum of the numbers on the gems he distributed. He told Tenali only that the
sum
was divisible by
N
and asked Tenali to find the number of possible sets of distributed gems.
Help Tenali to find the answer. Since the result may be big return the answer modulo 1,000,000,007.
Input
First line T the number of test cases (1 ≤ T ≤ 10)
Followed by T lines containing the value for N, K.
N the number Gems in the bag (1 ≤ N ≤ 1000000000).
K the number of Gems distributed (1 ≤ K ≤ Min(N, 1000)).
Output
Return the number of possible set of gems distributed modulo 1,000,000,007
Example
Input:
1
7 4
Output:
5
Explanation:
7 gems are numbered 0 to 6 and 4 of them were distributed. Possible sets of gems distributed are {0, 1, 2, 4}, {0, 3, 5, 6}, {1, 2, 5, 6}, {1, 3, 4, 6}, {2, 3, 4, 5}. | 34,000 |
Keyur and Mohib Tree (MOHIBTREE)
This Time Keyur (Singal) has been challenged by his friend Nishant (Vaju). As Keyur's programming skills are very poor, he asked you to help him. So as a great programmer you have to help Keyur. The challenge is as follows:
Keyur has given a binary tree Mohib-tree. Every Mohib-tree has the following properties:
Every Mohib-tree contains a root node that stores a positive integer greater than or equal to 2.
Every node of an Mohib-tree is either a leaf node (has no children) or has exactly 2 children which are Mohib-trees as well.
The sum of values of children nodes is always equal to the value of the parent node.
Value of at least one of the children nodes divides the parent value.
The height of the tree is defined as the number of edges from the root to the deepest leaf.
The following are valid Mohib-Trees:
6 6
/ \ / \
2 4 3 3
/ \
2 2
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case starts with one line with one integer N, which represents the value of the root node.
Output
For each test case, output one line containing "Case #x: ", where x is the test case number (starting from 1). Then, for every value N in the test case, output the maximum possible height of all Mohib-trees with root N.
Constraints
0 < T ≤ 20
2 ≤ N ≤ 10
14
Sample
Input:
3
2
6
31
Output:
Case #1: 0
Case #2: 2
Case #3: 0 | 34,001 |
Pisano Factors (PFACTORS)
Given an integer n.
Find how many integers c are there such that their Pisano period is a factor of n.
1 <= c <= 10^5
There are multiple test cases.
Input
The first line contains number of test cases, 1 <= t <= 100
Next t lines contain an integer n each. 1 <= n <= 10^9
Output
Output the answer to each test case on a separate line.
Example
Input:
3
6
9
10
Output:
3
2
2 | 34,002 |
detective sherlock holmes (DSH)
Detective Sherlock Holmes undertook a case, he found a clue against the culprit. He got a clue in lower case letters and he predicts that if he decodes these characters into respective numeric value, then he would find the culprit. the total number of individual numeric values that are greater than q’s numeric value is the required solution. Vexed of solving the case he is asking for your help, so please help him.
Input
There is several test cases and the last case is contained by “length of clue ≤ 3”,
each line contains a string (should contain only lowercase letters) (length of clue is (3 < l ≤ 26)).
Output
For each test case print two lines, the former containing the numeric value of string and the later containing the total number whose value is greater than q if not then print ”no one.”
Example
Input:
aknpz
luxo
aven
abcds
out
Output:
16 26 20 22 23
1
27 18 21 21
1
16 19 20 20
no one.
16 17 18 19 25
1
Problem Setter:- Farhan khan | 34,003 |
Bits. Exponents and Gcd (TOUGH)
Rastas's has been given a number n. Being weak at mathematics, she has to consider all the numbers from 1 to 2
n
- 1 so as to become perfect in calculations. (You can assume each number is consider as a soldier).
We define the strength of number
i
as the number of set bits (bits equal to 1) in binary representation of number
i
.
If the greatest common divisor of numbers
a
and
b
is
gcd
(
a
,
b
),
Rastas would like to calculate the function
S
which is equal to:
As the friend of Rastas, it's your duty to calculate
S
modulo 10
9
+ 7.
Input
The first line of the input contains the number of test cases,
T
. Each of the next
T
lines contains an integer
n
, as mentioned in the question.
Output
For each value of
n
given, find the value of the function
S
.
Constraints
Sum of
n
over all test cases doesn't exceed
2500
.
Example
Input:
3
1
2
5
Output:
0
3
680 | 34,004 |
Lights On! (TURNLT)
The problem is an interactive puzzle game. The puzzle given can be solved in multiple ways. You need to solve it in
minimum
number of clicks!
After solving the puzzle, You'll get a score.Enter the number(score) as PLAIN TEXT as your solution.
Since, there's only one way to solve the puzzle in minimum number of clicks, the score obtained for correct answer should be same.
Click here for the puzzle!
[ Edited By Min_25 ]
The puzzle is as follows:
RULES
The blocks represent the rooms. The lights in some of the rooms are on while others are off. You need to turn all the lights on. Clicking on a block will toggle the state. The only problem is that the other rooms which share an edge will also toggle. You need to solve the puzzle in minimum number of clicks. Print the number obtained as score as PLAIN TEXT on SPOJ.
(WHITE BLOCK-ON,BLACK BLOCK-OFF).
SCORE
Your initial score is 0. If you click on (x, y), your score will be increased by x * y.
The coordinates at the top-left corner and at the bottom-right corner are (1, 1) and (8, 8), respectively.
Input
NO PROBLEM INPUT.
Output
SCORE AS OUTPUT. | 34,005 |
Pointers (INC2015F)
You are given an R rows x C columns grid map where each cell contains an arrow (one of the following: '^', '>', '<', or 'v'). If one stands on a cell, then he/she has to go to the neighbouring cell pointed by the arrow in the cell where he/she stands. Supposed you are at cell (r, c) – row r and column c, then:
'^' means you should go to cell (r-1, c).
'>' means you should go to cell (r, c+1).
'<' means you should go to cell (r, c-1).
'v' means you should go to cell (r+1, c).
If the new cell is out of the grid map, then you fall out of the map.
Your task is to modify the arrows, such that if you start from any cell in the map and follow the arrows, then you will get back to the starting point. Determine the minimum number of arrows that you will have to change.
For example, consider the following map of 4 x 2.
>v
v<
>v
><
There are several ways to accomplish our goal; here are 3 solution examples:
>< v< >v
>< v^ ^<
>< v^ ><
>< >^ ><
In the first solution example, we have to change 3 arrows: {(1, 2), (2, 1), (3, 2)}. In the second one, we have to change 6 arrows: {(1, 1), (1, 2), (2, 2), (3, 1), (3, 2), (4, 2)}. In the last one, we have to change 2 arrows: {(2, 1), (3, 2)}. There are many other solution examples, but among those, the minimum number of arrows you need to change is 2 (as in solution example 3).
If the new cell is out of the grid map, then you fall out of the map.
Your task is to modify the arrows, such that if you start from any cell in the map and follow the arrows, then you will get back to the starting point. Determine the minimum number of arrows that you will have to change.
For example, consider the following map of 4 x 2.
>v
v<
>v
><
There are several ways to accomplish our goal; here are 3 solution examples:
>< v< >v
>< v^ ^<
>< v^ ><
>< >^ ><
In the first solution example, we have to change 3 arrows: {(1, 2), (2, 1), (3, 2)}. In the second one, we have to change 6 arrows: {(1, 1), (1, 2), (2, 2), (3, 1), (3, 2), (4, 2)}. In the last one, we have to change 2 arrows: {(2, 1), (3, 2)}. There are many other solution examples, but among those, the minimum number of arrows you need to change is 2 (as in solution example 3).
Input
The first line of input contains an integer T (T ≤ 100) denoting the number of cases. Each case begins with two integers R and C (1 ≤ R, C ≤ 14) denoting the number of rows and columns of the grid map. The following R lines each contains C characters (one of the following: '^', '>', '<', 'v') representing the arrow in each cell.
Output
For each case, output in a line "Case #X: Y" where X is the case number, starts from 1. and Y is the minimum number of arrows you need to change to accomplish the given goal. Output -1 for Y, if it's not possible to do so.
Example
Input:
4
4 2
>v
v<
>v
><
3 4
v<>v
v^^v
>^^<
3 4
v<<<
v^v<
>>>^
1 2
>>
Output:
Case #1: 2
Case #2: 0
Case #3: 2
Case #4: 1
Explanation:
Explanation for 2
nd
sample case
The map already satisfies the goal; there's no need to change any arrow.
Explanation for 3
rd
sample case
We need to change at least 2 arrows:
v<><
v^v<
>^>^
Explanation for 4
th
sample case
One arrow has to be changed:
>< | 34,006 |
Get higher and higher (MAXI)
You are travelling to Kullu Manali, a hill station in India. You saw some huge mountains and very curious to climb the highest ones. Assume that there are
n
mountains of height
hi
given.
But you were wondering about what could be the total height i need to climb if I climb only the mountain of maximum height only in a segment of k continuous mountains, considering all k segments possible. You want to calculate this for all k, such that 1 ≤ k ≤ n.
Mathematically, we need to find the sum of maximum element in each possible continuous segment of size k.
Input
The first line contains an input
n
.
Then
n
numbers follow, denoting the height of
ith
mountain.
Output
Output
n
lines, where ith line contains the sum of height of mountains to climb considering all continuous segments of size
i
.
Constraints:
1 ≤ n ≤ 10000
Example
Input:
5
5 3 4 2 3
Output:
17
16
13
9
5
Explanation
For k=1, all the contiguous segments are (5), (3), (4), (2), (3). The total sum of maximum in each segment is 17 (5+3+4+2+3).
For k=2, all the contiguous segments are (5, 3), (3, 4), (4, 2), (2, 3). The total sum of maximum in each segment is 16 (5+4+4+3).
For k=3, all the contiguous segments are (5, 3, 4), (3, 4, 2), (4, 2, 3). The total sum of maximum in each segment is 13 (5+4+4).
For k=4, all the contiguous segments are (5, 3, 4, 2), (3, 4, 2, 3). The total sum of maximum in each segment is 9 (5+4).
For k=5, all the contiguous segments are (5, 3, 4, 2, 3). The total sum of maximum in each segment is 5 (5). | 34,007 |
Corn Headache (CORN)
Once Jhon wanted to eat corn but the shopkeeper has many corns of different sizes having same price.
Jhon wants the bigger corn but When he observes all corns he found that many small size corns have more seeds than bigger one so he needs your help in choosing the corn.
As the corn shape is almost like cone and You are good in mathematics (assume you are :P) Jhon wants you to select the corn for him and tell him the total number of seeds on this corn.
Input
First line of input is 't' - number of test cases. In each of the next t lines There are three numbers, R - radius of the biggest part of corn, and S - The number of seeds in corn per cm
2
, and H - the height of the corn. This is in the following form:
ReSeH
R, S, H < 1000 and Pi = 3.1415
Output
Only one
integer
, the number of seeds on each corn.
Example
Input:
1
2e4e20
Output:
506 | 34,008 |
Crazy Smoker (CRZYSMKR)
The "
BHAI Group
" Of IIIT Allahabad is Famous For Many Things, Leading in Every Field Of College Activity
So One Day The
Leader Of Bhai Group
decided to smoke
C(N)
cigarettes each day:
-
F(N) = 34^N+ (30 x N) + 32
-
C(N) = F(N) mod (11)
, where
x mod y
is the
remainder obtained by dividing x by y
.
But
Bhai Group's Leader's Girlfriend
wants that he doesn't smoke any cigarette, so she made modifications:
-
F(N) = 34^N+ (30 x N) + (32 + M)
-
C(N) = F(N) mod (11)
Edit 1 : Time limit set to 0.100s
Problem Credits : IIIT Allahabad HE Club
Input
First line of each test case is an integer
T
, total number of test cases. Next
T
lines contains a single integer
N.
Output
Print the
minimum
value of
M
in single line for each test case.
Constraints
1 <= T <= 10^6
1 <= N <= 10^18
Example
Input:
2
1
2
Output:
3
6
Explanation:
For N = 1
F(N) = 34 + 30 + 32 = 96
So, M = 3
Now, C(N) = 99 mod(11) = 0
For N = 2
F(N) = 1156 + 60 + 32 = 1248
So, M = 6
Now, C(N) = 1254 mod(11) = 0 | 34,009 |
I LOVE Kd-TREES (ILKQUERY)
You've been invited to the "I-Love-Kd-trees" annual con, but first, you have to show them that you really know about great data structures, so they give you an easy task!
You are given a list of
N
numbers and
Q
queries, each query consist of three integers:
k
,
i
and
l
; let
d
be the
k-th
smallest element until the index
i
(i.e. if the first i+1 elements were sorted in non-descending way,
d
would be the element at index
k - 1
). Then, the answer to each query is the index of the
l-th
occurrence of
d
in the array. If there's no such index, the answer is
-1
. You have to consider that all indexes are counted starting with
0
.
Input
Input consists of one test case.
The first line contains two integers,
N
(1 ≤ N ≤ 10
5
) and
Q
(1 ≤ Q ≤ 10
5
).
The next line contains
N
possibly distinct integers
a
i
(-10
9
≤ a
i
≤ 10
9
).
Then
Q
lines follow, each of those contains three integers
k
,
i
and
l
. (0 < k ≤ i < N, 1 ≤ l ≤ N).
Output
For each query (in the same order as the input) output a single line with the answer to that query.
Example
Input:
10 6
2 6 7 1 8 1 2 3 2 6
2 4 2
2 6 3
1 4 1
1 4 2
3 4 2
3 3 2
Output:
6
-1
3
5
9
9
Explanation of the first query:
The elements until index 4 are [2, 6, 7, 1, 8] so the 2nd smallest element is 2, and your asked for the index of its 2nd occurrence, so the answer is 6. | 34,010 |
Related or not (NINJA1)
You are given two DNA sequences A and B. It is said that these two DNA sequences are related if there exists a non-decreasing sequence C of the same length, such that C
i
= A
i
or C
i
= B
i
. Find if the given sequences are related.
Input format:
The first line contains an integer,
T
, the number of test cases.
For each test case:
The first line contains an integer,
N
, the length of the DNA sequence.
The second line contains a sequence of space-separated integers describing species
A
.
The third line contains a sequence of space-separated integers describing species
B
.
Output Format
On a new line for each test case, print
YES
if a non-decreasing sequence of the same length can be found or
NO
if it cannot.
Constraints:
1 ≤ T ≤ 5
1 ≤ N ≤ 10
5
0 ≤ A
i
, B
i
≤ 10
10
Sample:
Input:
3
3
1 2 3
4 4 4
3
3 2 1
6 5 4
2
1 0
10 2
Output:
YES
NO
YES | 34,011 |
PATHETIC STRINGS (NINJA2)
A string is said to be “PATHETIC” if all the characters in it are repeated the same number of times. You are given a string of length n, what is the minimum number of changes required to make a string “PATHETIC”. The string has only lower case letters and you can change any letter to any other letter.
Input Format
The first line contains an integer T, the number of test cases. This is followed by T test cases each containing 1 line: Each testcase consists of a string composed of lowercase letters.
Output Format
For each testcase, print in a new line the minimum number of changes required.
Constraints
1 ≤ T ≤ 1370
1 ≤ n ≤ 1991
Sample
Input:
2
bbaccaaa
ccaacb
Output:
2
1 | 34,012 |
STUNNING GCD (NINJA3)
You are given three numbers N, a, b. You can build a number X by repeating N 'a' times and the number Y by repeating N 'b' times. Now that you have the numbers X and Y, determine the GCD of the two numbers X and Y.
Input
The first line contains an integer T, the number of test cases.
Then for each test case, there are three integers in each line:
N, a, b
.
Output
Print the required answer for each test case in a single line.
Constraints
1 ≤ T ≤ 100
1 ≤ N, a, b ≤ 10
18
Sample
Input:
1
123 2 3
Output:
123 | 34,013 |
HELP SHELDON (NINJA4)
Dr. Sheldon Cooper builds a MVPD replication of himself which he calls a "Mobile Virtual Presence Device" (MVPD) that would go through all the hazards of life that he would otherwise have to experience while he stays behind in a "secure, undisclosed location". Now the MVPD is initially standing at the origin of the Cartesian coordinate system, (0, 0). (More like Sheldon's spot (0, 0, 0, 0)). Then the MVPD makes N turns:
On the first turn, the MVPD goes 1 unit to the right.
On the second turn, the MVPD goes 2 units up.
On the third turn, the MVPD goes 3 units to the left.
On the fourth turn, the MVPD goes 4 units down.
On the fifth turn, the MVPD goes 5 units to the right.
And so on.
Given an integer N, find the position of Sheldon's MVPD so that he won't get lost somewhere.
Input Format
The first line contains a single integer, T, denoting the number of test cases.
For each test case, a single line contains a single integer - the value of N.
Output format:
For each test case output a single line, containing two integers - the coordinates of the MVPD after performing N turns.
Constraints:
1 ≤ T ≤ 100.
1 ≤ N ≤ 10
9
.
Sample:
Input:
2
3
4
Output:
-2 2
-2 -2 | 34,014 |
K NUMBERS (NINJA5)
You are given N numbers from 1 to N. Now, your task is to choose some numbers from the N numbers (including 1 and N) such that no two numbers are
consecutive
. As this is easy, you are given an extra task. You have to definitely choose K numbers which are given. Find the maximum number of numbers that you can choose in such a way.
Input
The first line has an integer T, the number of test cases.
Then for each test case, the first line has two integers N and K.
Then the next line has K numbers which you should definitely choose.
Output
For each test case, print the maximum number of numbers that you can choose.
Constraints
1 ≤ T ≤ 100
2 ≤ N ≤ 2 x 10
6
1 ≤ K ≤ N / 2
1 ≤ X[1...K] ≤ N
Example
Input:
1
8 2
6 2
Output:
4 | 34,015 |
TRAVELLING DILEMMA (NINJA6)
A graph of a country is given. There are N cities and M number of roads. Each road connects two cities. Now you are given two modes of traveling from one city to another.
By using public transportation.
By using your own car. (Which you can use
only once
between any two cities on your way). You may or may not use this mode of travel.
The country's map is given as a graph with N nodes (labeled from 1 to N), and the initial station is node S and the destination is node D. There are two undirected edges between each of the given nodes:
one denotes the cost of a path using public transportation, r.
and the other denotes the cost of a path using your own car, t.
Now you have to find the most optimal way (in terms of time of cost) from S to D with or without using your entitled car ride.
Output the minimized cost of your travel from the source to the destination.
Input:
The first line contains T, the number of test cases.
For each test case:
The first line contains two space-separated integers, N (the number of cities in the map) and M (the number of roads in the map), respectively.
The next M lines each have four space separated integers c1, c2, r, and t, respectively; c1 and c2 denote two cities connected by a road, r is the cost for using the public transportation, and t is the cost of taking your own car on the road.
The last line has two space-separated integers, S (Starting city) and D (Destination), respectively.
Output:
For each test case, print a single line with minimum travel cost. If the destination (D) is unreachable from the source node (S), print −1.
Constraints:
1 ≤ T ≤ 10
2 ≤ N ≤ 3000
1 ≤ M ≤ N×(N−1)
1 ≤ x, y, S, D ≤ N
1 ≤ r, t ≤ 500
Sample:
Input:
1
4 5
1 2 6 5
1 3 4 5
2 3 6 1
2 4 3 4
3 4 5 7
1 4
Output:
8 | 34,016 |
TWO SEQUENCES PROBLEM (NINJA7)
Given two lists A and B having the same length, find the length of longest subsequence of list A, whose sum is greater than or equal to the corresponding subsequence of list B. Corresponding subsequence means indices chosen in both of the lists must be the same.
Input
The first line contains an integer
T
, the number of test cases.
Then for each test case, there are 3 lines.
The first line has an integer N, the number of elements in the lists A and B.
The second line contains N integers of the list A.
The third line contains N integers of the list B.
Output
For each test case, print the answer in a single line.
Constraints
1 ≤ N ≤ 10
5
0 ≤ A[i] ≤ 10
7
0 ≤ B[i] ≤ 10
7
Sample
Input:
1
3
100 100 5
2 2 1000
Output:
2 | 34,017 |
George vs Kramer (NINJA8)
George and Kramer are in a serious fight. Seeing this, Jerry comes to convince them and settle the fight with a reasonable task. Knowing about their fondness of stamps, he creates a wonderful task for them. They are given N containers each having one or more stamps. Containers are numbered from 1 to N, where ith container has A[i] number of stamps. The game goes as follows. The first player will choose a container and take one or more stamps from it. Then, the second player will choose a non-empty container and take one or more stamps from it. And then they repeat this alternatively. This process will continue, until one of the players is not able to take any stamps, i.e., there are no stamps left. One who is not able to take any stamps loses the game. Note that player can choose only non-empty container.
Luckily George somehow got the first chance. He wants to know the number of ways to make a first move such that under optimal play, he wins. Being so poor at math and programming, he asks for your help. Help him!
Input Format:
The first line has an integer T, the number of test cases.
Then for each test case, the first line contains an integer N, i.e., number of containers and the second line contains N integers, i.e., number of stamps in each of the containers separated by a single space.
Output Format
Print the number of ways to make the first move such that under optimal play, George always wins. If he cannot win under optimal play, print 0.
Constraints
1 ≤ T ≤ 50
1 ≤ N ≤ 10
6
1 ≤ A[i] ≤ 10
9
Sample
Input:
1
2
2 3
Output:
1 | 34,018 |
Power and Mod (PWRANDMOD)
Exponentiation is a mathematical operation, written as
b
n
, involving two numbers, the base
b
and the exponent
n
. When
n
is a positive integer, exponentiation corresponds to repeated multiplication of the base: that is,
b
n
is the product of multiplying
n
bases:
b
n
= b × b × b × ... × b
In computing, the modulo operation finds the remainder after division of one number by another (sometimes called
modulus
). Given two positive numbers,
a
(the dividend) and
n
(the divisor),
a
modulo
n
(abbreviated as
a
mod
n
) is the remainder of the Euclidean division of
a
by
n
. For instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3.
Now, you are given the value of a, b and m. print the value of
a
b
mod m
.
Input
First line contains the number of test cases t (1 ≤ t ≤ 10
4
). Next t line contains three integers a, b and m. where 1 ≤ a, b ≤ 10
9
and 1 ≤ m ≤ 2
64
.
Output
For each test case print the answer of the problem.
Sample input
2
2 3 4
3 4 5
Sample output
0
1 | 34,019 |
Harish and his rooks puzzle (HARISH_PUZZLE)
Harish is playing Eight Rooks Puzzle. In this puzzle, he must put exactly eight rooks onto an 8x8 chessboard. No two rooks must be in the same row, and no two rooks must be in the same column.
You are given a 8 × 8 board. The j-th column of the i-th row of board is either 'R' or '.'. If this is 'R', the cell in row i, column j contains a rook. Otherwise the cell doesn't contain a rook. Determine whether Harish solved the puzzle correctly. If he solved the puzzle correctly, print "YES". Otherwise print "NO".
Input
T - Number of test cases
Each test case contains a 8 × 8 character array indicating the chess board.
Each character in board will be either 'R' or '.'
Output
YES or NO indicating whether he has solved the puzzle.
Example
Input:
2
R.......
.R......
..R.....
...R....
....R...
.....R..
......R.
.......R
......R.
....R...
...R....
.R......
R.......
.......R
..R.....
.......R
Output:
YES
NO | 34,020 |
Alicias Afternoon Amble (AMBLE)
Alicia is staying in a hotel on the edge of town. She sets out in the morning with a list of landmarks to visit all across the city. This day of sightseeing will take her through the city, visiting a number of locations, all the way to the far-side of city where she will pause for lunch at the prestigious Pete’s Polygon Pizza Parlour. Anything she misses must be visited on the return trip to the hotel in the evening.
Given the set of locations that Alicia would like to visit, find the length of the shortest tour which starts at her hotel, visits each of the locations, and returns back to the hotel. Beside the starting location, each location should be visited exactly once.
The starting hotel will be located at the leftmost x-coordinate. From there, the optimal path should visit locations at strictly increasing x-coordinates until Pete’s Parlour is reached at the rightmost x-coordinate. From here, the optimal return path should visit any and all unseen locations in strictly decreasing x-coordinates.
Note that the x-coordinate of each location will be unique.
Input
The first line of input contains a single integer N, 1 ≤ N ≤ 1000, representing the number of locations.
Each of the next n lines contains two integers X and Y, 0 ≤ X, Y ≤ 100000, representing the coordinates of the N locations.
The (X, Y) coordinates of all locations are given as integers on a Euclidean plane.
Output
The output should consist of a single decimal containing the the total length of the tour rounded to two decimal places. This should immediately be followed by a newline.
Example One
Input:
5
1 3
2 1
3 4
4 4
5 2
Output:
10.87
Example Two
Input:
10
4 1
13 4
21 3
25 9
28 10
42 1
43 2
50 4
67 10
68 9
Output:
131.65 | 34,021 |
Palindromic Primes (Hard) (PALPRIM)
A Palindromic number is a number without leading zeros that remains the same when its digits are reversed. For instance
5, 22, 12321, 101101
are Palindromic numbers where as
10, 34, 566, 123421
are not. A Prime number is a positive integer greater than
1
that has no positive divisors other than
1
and itself. For example,
2, 31, 97
are Prime numbers but
1, 10, 25, 119
are not. A Palindromic Prime number is both palindromic and prime at the same time.
2, 3, 131
are Palindromic Prime numbers but
6, 17, 3333
are not. Given a positive integer
N
, output the largest palindromic prime number not greater than
N
.
Input
The first line contains an integer
T
denoting the number of test cases. Each of the subsequent
T
lines contain a single integer
N
without leading or trailing spaces.
Output
Print
T
lines. For each test case, print a single integer denoting the largest palindromic prime number which does not exceed
N
.
Constraints
1 ≤ T ≤ 10
6
2 ≤ N ≤ 10
13
Example
Input:
3
2
10
666
Output:
2
7
383
Note
Large input and output, please use faster I/O methods. | 34,022 |
DIVSEQ (DIVSEQ)
You're given two numbers - N and K (0 < N, K ≤ 1000). You have to count the number of sequences of
positive integers
with length N where every element must be not greater than K and for every two consecutive elements with indices i and i + 1 one of the conditions bellow must be true:
a[i] is divisible by a[i + 1]
a[i + 1] is divisible by a[i]
Input
On the only line you will be given the values of N and K.
Output
Print the number of the sequences described above modulо 1000000009.
Example
Input:
2 4
Output:
12 | 34,023 |
Pair Divisible 2 (PAIRDIV2)
Let $C(N, a, b)$ be the number of integer pairs $(x, y)$ in $1 \le x \le a$, $1 \le y \le b$ such that $xy$ is divisible by $N$.
Given $N$, $a$ and $b$, find $C(N, a, b)$
modulo
$10^{9}$.
Input
The first line contains $T$, the number of test cases.
In each of the next $T$ lines, you are given three numbers $N$, $a$ and $b$.
Output
For each test case, print $C(N, a, b)$
modulo
$10^{9}$.
Constraints
$1 \le T \le 100$
$1 \le N \le 10^{18}$, $1 \le a \le 10^{18}$, $1 \le b \le 10^{18}$.
You can assume that the
maximum prime factor
of $N$ is less than or equal to $10^{5}$.
Example
Input
5
1 1 1
2 2 2
10 10 10
100 100 100
1 10000 100000
Output
1
3
27
520
0 | 34,024 |
Grand Reward (GR)
Grand is one of the best companies every month, The manager chooses the best employee and rewards him. This month there are 4 employees do the same effort Sameh, Ameen, Shafeek and Atef but the manager will give reward to one only, He got a good idea
Let's say that the 4 employees will stand in someway like that every employee in one of the four sides east (Sameh), north (Ameen), west( Shafik) and south (Atef) then, there's a square matrix of width and height N×N among them first element in matrix will start with 1 then next element increase by 1 from left to right and from top to down until N×N like this:
Ameen
1 2 3
Sameh 4 5 6 Shafeek
7 8 9
Atef
Then let's rotate the matrix T turns 90 degrees clockwise per turn and the winner is the person who the sum of his side is the greatest.
For example let's say that T=4 and N=3,
first rotation second rotation third rotation fourth rotation
Ameen Ameen Ameen Ameen
7 4 1 9 8 7 3 6 9 1 2 3
Sameh 8 5 2 Shafeek Sameh 6 5 4 Shafeek Sameh 2 5 8 Shafeek Sameh 4 5 6 Shafeek
9 6 3 3 2 1 1 4 7 7 8 9
Atef Atef Atef Atef
Atef wins because the sum of his side is 7 + 8 + 9 = 24 and it's the greatest.
It's your job now create a program that do this job.
Input
Two integers the size of the matrix N (3 ≤ N ≤ 25), and the number of turns (1 ≤ T ≤ 10
9
).
Output
The final result of the matrix and the employee who will get the reward (Sameh, Ameen, Shafeek, Atef).
Example
Input:
3 4
Output:
Atef
1 2 3
4 5 6
7 8 9
Input:
4 3
Output:
Shafeek
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13 | 34,025 |
CODER FIRST PROBLEM (CDRSANJ)
Coder Sanjay
is now ready to put up his first problem in his favorite website
SPOJ
. As it is his first problem, he wanted it to be easy so that most of them could get an
AC
.
The problem statement looks like this:
F(x)
is a function whose properties are as follows.
F(x) = 0
at x = 0.
F(x) = 1
at x = 1.
F(x) = 2
at x = 2.
F(x) = 0
if x is an odd prime.
F(a*b) = F(a) + F(b)
, where a, b are two positive integers and sum of a and b is minimum.
Your task is simple. You are to output the value of
F(x)
for the given input integer
x
.
Input
The only line of input contains a single integer
x
(0 < x < 100001).
Output
Output the value of
F(x)
.
Example
Input:
4
Output:
4 | 34,026 |
An easy Problem (ADDAP)
Seeing so much companies coming for placement in ISM, BABBU also started coding. After rigorous coding for two months, he got bored in solving problems. Now he wants to become problem setter. In order to set problems he took advice from his friends GOTU and CHHOTU. After having a heavy discussion they came up with a problem which goes like this...
You are given a tree rooted at 1.
And you are given Q number of queries to perform on tree.
For each query you are given u, x and y, where u denotes the node number.
You have to add value x to the node u, x + y to its all children at depth 1 (one), x + 2y to all its children at depth 2, ... x + d*y to all its children at depth d and so on.
Input
First line of input contains N - total number of nodes in tree.
Next N-1 lines contain u and v, i.e. there is and edge between nodes u and v.
Next line contains a single integer Q, indicating total number of queries to perform on tree.
Next Q lines contain u x y.
1 <= N <= 100000
1 <= u <= N
1 <= x, y <= 100000
1 <= Q <= 100000
Output
You have to output final values of each node from 1 to N after performing Q queries.
Since the values may be large print them modulo 1000000007.
Sample
Input:
10
4 9
6 4
7 10
5 3
2 6
1 5
5 10
3 8
7 2
5
7 8 1
1 10 7
7 4 7
1 4 1
2 6 2
Output
14
72
30
108
22
90
50
38
126
30 | 34,027 |
Factorial and divisorss (FACTDIV)
You have given number of test cases.
Each test case have two space separated integer L and R. You have to find total value of fun(L) + fun(L+1) + ... + fun(R), where fun(x) is total number of positive divisors of x factorial. Since result may be large print it modulo 1000000007.
Input
First line of input contains T total number of test case.
Next T lines contain two space-separated integers L and R.
1 <= T <= 1000000
1 <= L <= R <= 1000000
Output
For each test case output the result modulo 1000000007.
Example
Input:
10
1 9
6 7
2 4
7 8
1 3
10 10
3 5
6 7
1 10
6 6
Output:
377
90
14
156
7
270
28
90
647
30 | 34,028 |
Theater shade in Berland (TAXI2)
In Berland a new movie was released on the occasion of 14th Feb. The craze for this movie was very much among the peoples of the city. So many of them decided to go to the only movie theatre of Berland. As Berland is very much developed there are many large buildings, including the movie theatre. At each building except the theatre, there exists either a person who wants to see the movie or a taxi driver with his taxi. As it is very late in the night each taxi driver will only accommodate one passenger and also he will only drive for
T[i]
hours (return journey is not included). You will be given the distance between building
D[i]
and the speed of each taxi driver
S[i]
. As I am the owner of this theatre help me by telling, the maximum number of people I will see in the theatre for the movie.
N + P + 1
th building is the my theatre. Also, if a taxi starts his journey by taking a passenger, it only stops at the theatre.
Input
First line contains
TT
the number of test cases.
First line of each test test case contains
N
,
P
and
R
denoting the number of taxi, number of people, and the number of roads between buildings.
Next line contains
N
space-separated integers representing the building where taxi is present.
Next line contains
P
space-separated integers representing the building where passengers is present.
Next
R
lines contains
X
,
Y
, and
D[i]
the building connected via road and the distance between them in km.
Next line contains
N
space-separated integers
S[i]
giving the speed details of each taxi in km/h.
Next line contains
N
space-separated integers
T[i]
giving the time details of each taxi in hours.
Output
Maximum number of people that will visit my theatre.
Constraints
1 ≤ TT ≤ 5
1 ≤ N ≤ 500
1 ≤ P ≤ 1000
1 ≤ R ≤ 50000
1 ≤ X, Y ≤ N
5 ≤ S[i] ≤ 50
1 ≤ T[i] ≤ 5
1 ≤ D[i] ≤ 100
Example
Input:
1
1 2 4
2
1 3
1 2 5
2 3 5
3 4 10
1 3 8
20
1
Output:
1 | 34,029 |
I Love Kd-Trees II (ILKQUERY2)
Every time someone is preparing to be interviewed, there is someone preparing the interview. While a good guy is preparing for the interview described in
ILKQUERY
your boss gives you the job of preparing the input/output for a new task.
But as always, your boss changes his mind so quickly... He will give you an array of integers, but sometime, he will say you that the element at index
r
of the original array must toggle his state between active (1) and inactive (0).
Initially all elements start as active elements.
Toggle the state of an element means to change it to active (1) if it was inactive, and change it to inactive (0) if it was active.
Mixed with the toggle operations, he also will give you several queries, represented with three integers,
i l k
meaning he wants to know how many active elements of value
k
exist between indexes
i
and
l
(both inclusive).
Input
Input consists of one test case.
The first line contains two integers,
N
(1 ≤ N ≤ 10
5
) and
Q
(1 ≤ Q ≤ 10
5
).
The next line contains
N
integers
a
i
(-10
9
≤ a
i
≤ 10
9
).
Then
Q
lines follow. Each of them starts with an integer
q
which can be 0 or 1. If it's 0, then three integers
i l k
follow (0 ≤ i < N ; i ≤ l < N ; -10
9
≤ k ≤ 10
9
). If it's 1, then an integer
r
follows, meaning you have to toggle the state of the element at index
r
. (0 ≤ r < N).
Output
For each query starting with 0 (in the same order as the input) output a single line with the answer to that query. That is, output the amount of active elements of value
k
between the indexes
i
and
l
(both inclusive).
Example
Input:
10 5
2 2 3 2 1 5 4 2 6 3
0 0 7 2
1 3
0 0 7 2
1 6
0 2 7 4
Output:
4
3
0 | 34,030 |
Atul and Aastha Chronicles 2 (AAC2)
Atul loves gifting chocolates and Aastha loves eating them but excess of anything is bad and same goes for chocolates. Eating all those chocolates has made Aastha overweight and she needs to watch her weight now. So she has to classify the chocolates based on their sugar content. She gave this task to Jaya. After completing the task Jaya is still not confident. She wants you to check whether her classification is correct or not. Basically if two chocolates have the same sugar level they are represented as a=b else they are represented as a!=b. You are given a list of binary relations, equalities and inequalities, like a = b, a != d, b = c etc. Your task is to output YES if the classification is correct , that you can satisfy all equalities and inequalities. Otherwise you should output NO.
Input
In the first line there is one integer T denoting the number of test cases. Description of T test cases follow. Each one have two integers N and K given in the first line denoting the number of variables and the number of relations between them for this test case. All variables are represented by integers in range [1, N]. K lines follow. Each of them is of the form "x1 R x2" where x1 and x2 are integers representing variables and R is either "=" or "!=" and denotes the kind of relation between these variables.
1 <= N, K <= 10^6
Output
Output exactly T lines. In i-th of them, output the answer to the i-th test case.
Example
Input:
2
2 2
1 = 2
1 != 2
3 2
1 = 2
2 != 3
Output:
NO
YES | 34,031 |
All about Sorting! (MINDIFF)
You will be given three sorted arrays. Let’s denote the three arrays as A, B and C.
Your task is fairly very simple. You just have to find one element from each of the three arrays so that
(|A
i
-B
j
| + |B
j
-C
k
| + |C
k
-A
i
|)
is the smallest. Here A
i
is an element from array A. B
j
is an element form array B. C
k
is an element form array C.
Input
The first line of the input will be an integer T denote the number of test cases.
For each of the test cases there will three integers
Na Nb Nc
in the first line. Na will denote the size of array A, Nb will denote the size of array B, Nc will denote the size of array C.
In the second line of each test case there will be Na number of integers denoting the elements of array A.
In the third line of each test case there will be Nb number of integers denoting the elements of array B.
In the fourth line of each test case there will be Nc number of integers denoting the elements of array C.
Output
For each test case print the desired result.
Constraints
1 <= t <= 100
1 <= Na, Nb, Nc <= 1000
Each elements of the arrays will be a non-negative number less than 10^9.
Example
Input:
2
3 2 3
2 4 6
5 7
1 3 5
3 5 4
1 3 5
7 8 9 10 11
2 14 20 36
Output:
2
10 | 34,032 |
Path Game (PATHGAME)
Cat Snuke is playing the Path Game.
The Path Game is played on a rectangular grid of square cells. The grid has 2 rows and some positive number of columns. Each cell is either black or white.
A left-to-right path in the grid is a sequence of white cells such that the first cell in the sequence is in the leftmost column, the last cell in the sequence is in the rightmost column, and each pair of consecutive cells shares a common side.
The initial coloring of the grid is such that there is at least one left-to-right path. You are given this initial coloring as a 2D string. For each i and j, grid[i][j] is either '#' (representing a black cell) or '.' (representing a white cell).
Snuke may color some of the white cells black. After he does so, there must still be at least one left-to-right path left on the board. The goal of the game is to color as many cells black as possible. Compute and return the largest number of cells Snuke can color black. (Note that the cells that are already black do not count.)
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts with an integer N (1 ≤ N ≤ 50), denoting the length of each row of the grid. Next two lines describe the 2D grid. Each line contains N characters ‘.’ or ‘#’. It is guaranteed that the grid will contain a left-right-right path.
Output
For each case, print one line containing the answer to the problem.
Example
Input:
2
5
#....
...#.
25
....#.##.....#...........
..#......#.......#..#....
Output:
2
13 | 34,033 |
Sort Machine (SORTMAC)
We have a sorting machine that works on a list of distinct numbers. This machine only has two instructions, named MOVEBACK and MOVEFRONT. Each instruction takes one element of the list as a parameter and removes that element from the list. MOVEBACK will then append that element to the end of the remaining list, while MOVEFRONT will insert it at the beginning.
For example, the sequence {8, 12, 25, 7, 15, 19} can be sorted in ascending order using 2 instructions:
MOVEFRONT 7, to get {7, 8, 12, 25, 15, 19}
MOVEBACK 25, to get {7, 8, 12, 15, 19, 25}
You will be given a list of distinct numbers. Compute the minimum number of instructions required to sort the list in ascending order.
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts with an integer N (1 ≤ N ≤ 50), denoting the number of elements. Next line consists N distinct elements. Each element will be between -1000 and 1000.
Output
For each case, print one line containing the answer to the problem.
Example
Input:
3
6
8 12 25 7 15 19
5
1 2 3 4 5
5
1 -10 -1 -8 4
Output:
2
0
3 | 34,034 |
Gutibazi (NUMPATH)
Xunayed is furious. He found out that his friend Nurulla who is just like his brother (tore ami bae bhabsilam), did some gutibazi with him. Xunayed can forgive anything, but gutibazi is something he can never forgive. But to give Nurulla a lesson Xunayed first has to go to Nurulla through some path. Then the problem occurs. Roads belong to a very powerful individual named Rizvi and everyone has to take permission from him to pass those roads. Rizvi will give permission to Xunayed only if Xunayed can solve a riddle.
Path is some 2d grid. Xunayed is currently on upper left cell (cell (1,1) in the figure below) which is source. Nurulla is now on lower right cell (cell (3,3) in the figure below) which is destination. Xunayed can only go down/right from his current cell.
In how many ways there exists a path where Xunayed can reach Nurulla.
1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3
Solve this riddle to help innocent Xunayed and bring forth justice.
Input
Input starts with an integer
T (≤ 50)
, denoting the number of test cases.
Each case starts with a line containing two integers
R C (1 ≤ R, C ≤ 7)
, where
R
denotes the number of rows and
C
denotes the number of columns of the grid respectively.
Output
For every test case, output an integer which represents the number of ways Xunayed can reach Nurulla.
Example
Input:
2
1 1
2 2
Output:
1
2 | 34,035 |
I LOVE Kd-TREES III (ILKQUERYIII)
The "I-Love-Kd-trees'' annual con is receiving too many applicants so they decided to complicate a bit the task used to select participants. (They realized some people were using other data structures to solve their problems, so they designed this problem, almost only solvable with Kd-trees).
You are given a list of
N
numbers and
Q
queries. Each query can be of two types.
Type-0
queries (marked with 0 in the input), consist of three integers:
i,
l
and
k
; let
d
be the
k-th
smallest element until the index
i
(i.e. if the first i +1 elements were sorted in non-descending way,
d
would be the element at index k - 1). Then, the answer to each query is the index of the
l-th
occurrence of
d
in the array. If there's no such index, the answer is -1.
Type-1
queries (marked with 1 in the input) are contiguous-swap update-queries, and consists of a single integer
i
. When a type-1 query is executed the elements at index i and i +1 in the list must be swapped.
You have to consider that all indexes are counted starting with 0.
Input
Input consists of one test case.
The first line contains two integers,
N
(1 ≤ N ≤ 10
6
) and
Q
(1 ≤ Q ≤ 10
5
).
The next line contains
N
possible distinct integers
a
i
(-10
9
≤ ai ≤ 10
9
).
Then
Q
lines follow. Each of them starts with an integer which can be 0 or 1, denoting the type of the query. If it’s 0, then three integers
i
,
l
and
k
follow (0 ≤ i < N, 1 ≤ k ≤ i+1, 1 ≤ l ≤ N).
If it’s 1, then an integer
i
follows, meaning that you have to swap the elements at indexes i and i+1 (0 ≤ i ≤ N-1).
Output
For each query of type-0 (in the same order as the input) output a single line with the answer to that query.
Example
Input:
10 6
2 3 1 1 2 7 9 1 2 6
0 2 3 2
1 1
1 2
0 2 3 2
1 0
0 0 2 1
Output:
8
7
2 | 34,036 |
Wonowon (WONOWON)
There is a little village in northern Canada called Wonowon, its name coming from the fact that it is located at Mile 101 of the Alaska Highway. While passing through this village, a wandering mathematician had an idea for a new type of number, which he called a wonowon number. He defined a wonowon number as a number whose decimal digits start and end with 1, and alternate between 0 and 1. Thus, the first four wonowon numbers are 101, 10101, 1010101, 101010101.
Neither 2 nor 5 can divide any wonowon number, but it is conjectured that every other prime number divides some wonowon number. For example, 3 divides 10101 (i.e. 3×3367), 7 divides 10101 (i.e. 7×1443), 11 divides 101010101010101010101 (i.e. 11 × 9182736455463728191).
Assume throughout that this conjecture is true, and let W(p) denote the number of digits in the smallest wonowon number divisible by p. Thus, for example, W(3) = 5, W(7) = 5, W(11) = 21, W(13) = 5, W(17) = 15, W(19) = 17.
It has been found experimentally that for many primes p, W(p) = p − 2 (as in the case for p = 7, 17, 19). Thus, your task is to write a program which reads an integer n and outputs the number of primes for which W(p) = p − 2. Note that p cannot be 2 nor 5, and p is a prime number less-than or equal to n.
Input
The input consists of a single integer 3 ≤ n ≤ 10000.
Output
The output should consist of a single integer representing the number of primes p for which W(p) = p − 2.
Example One
Input:
20
Output:
3
Example Two
Input:
100
Output:
14 | 34,037 |
Coverage (SERCOVERAGE)
A cellular provider has installed n towers to support their network. Each tower provides coverage in a 1km radius, and no two towers are closer than 1km to each other. The coverage region of this network is therefore the set of all points that are no more than 1km away from at least one tower. The provider wants as much of this region as possible to be connected, in the sense that a user at any point within a connected subregion can travel to any other point within the connected subregion without having to exit the subregion. Their current installation of towers may or may not already form a single connected region, but they have the resources to build one more tower wherever they want, including within 1km of an existing tower. Given that the provider is able to build one more tower, what is the maximum number of towers (including the new one) that can be included within a single connected subregion of coverage?
Input
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. The first line of input consists of a single integer n (1≤n≤5,000) denoting the number of existing towers. Next follow n lines, each with 2 space separated floating-point numbers x and y (0≤x,y≤100,000), denoting the location of a tower in km. It will be guaranteed that the optimal number of towers will not change even if the coverage radius of all the towers is increased or decreased by 10
-6
km.
Output
Ouput a single integer, denoting the maximum number of towers that can be within a single connected subregion of the network after installing one additional tower.
Example
Input:
5
1.0 1.0
3.1 1.0
1.0 3.1
3.1 3.1
4.2 3.1
Output:
6 | 34,038 |
Grid (SERGRID)
You are on an n x m grid where each square on the grid has a digit on it. From a given square that has digit k on it, a Move consists of jumping exactly k squares in one of the four cardinal directions. A move cannot go beyond the edges of the grid; it does not wrap. What is the minimum number of moves required to get from the top-left corner to the bottom-right corner?
Input
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. The first line of input contains two space-separated integers n and m (1≤n,m≤500), indicating the size of the grid. It is guaranteed that at least one of n and m is greater than 1. The next n lines will each consist of m digits, with no spaces, indicating the n x m grid. Each digit is between 0 and 9, inclusive. The top-left corner of the grid will be the square corresponding to the first character in the first line of the test case. The bottom-right corner of the grid will be the square corresponding to the last character in the last line of the test case.
Output
Output a single integer on a line by itself representing the minimum number of moves required to get from the top-left corner of the grid to the bottom-right. If it isn’t possible, output -1.
Example
Input:
5 4
2120
1203
3113
1120
1110
Output:
6 | 34,039 |
Gears (SERGEARS)
A set of gears is installed on the plane. You are given the center coordinate and radius of each gear, which are all integer-valued. For a given source and target gear, indicate what happens to the target gear if you attempt to turn the source gear. Possibilities are:
The source gear cannot move, because it would drive some gear in the arrangement to turn in both directions.
The source gear can move, but it is not connected to the target gear.
The source gear turns the target gear, at a certain ratio.
If the source gear cannot move, give this result, even if the source and target gears are not connected.
Input
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. The first line of input contains a single integer
n
(1 ≤
n
≤ 1,000), the total number of gears. Following this will be
n
lines, one per gear, containing the
x
,
y
(-10,000 ≤
x
,
y
≤10,000) and
r
(1 ≤
r
≤ 10,000) values for the gear, where (
x
,
y
) is the position of the axle of the gear, and
r
is its radius. Assume that the teeth of the gears are properly designed, and accounted for in the radius, so that any gear will mesh with any other gear if (and only if) they are tangent to each other. The gears will never overlap.
Output
Output a single line, with the following content, based on the result:
"-1"
- if the source gear cannot move.
"0"
- if the source gear can move but is not connected to the target.
"a b"
- if the source gear moves the target gear, where
a
and
b
are two space-separated integers, and
a
:
b
is the ratio of source gear revolutions to target gear revolutions reduced to its lowest form (i.e. they have no common factor other than 1).
a
is always positive.
If the target turns in the same direction as the source,
b
is positive.
If the target turns in the opposite direction as the source,
b
is negative.
Example
Input:
16
10 10 5
20 10 5
30 10 5
40 10 5
10 20 5
20 20 5
30 20 5
40 20 5
10 30 5
20 30 5
30 30 5
40 30 5
10 40 5
20 40 5
30 40 5
40 40 5
Output:
1 1 | 34,040 |
Almost Prime Numbers Again (KPRIMESB)
Almost Prime Numbers are composite numbers which are not divisible by certain prime numbers. Given K prime numbers and an integer N, find out the number of Almost Prime Numbers (i.e. composite numbers not divisible by any of the given K prime numbers) that are not greater than N.
Input
First line of input consists of an integer
T (1 ≤ T ≤ 1000)
, denoting the number of test cases. Then
T
test cases follow. Each case begins with a line containing two integers
N (0 ≤ N ≤ 10
6
)
and
K (1 ≤ K ≤ 10)
. The next line contains
K
space separated prime numbers. All the prime numbers are guaranteed to be
less than 50
.
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 Almost Prime Numbers that are not greater than N.
Example
Input:
2
1000 3
2 3 5
49 3
2 3 5
Output:
Case 1: 100
Case 2: 1 | 34,041 |
Lets Be An Anagrammatist (ANGRMTST)
Do you know what is an anagram?
An anagram is a rearrangement of letters of one word to form another word
. For example: one of the anagram of the word “CODEMASK” can be “DEMOCSAK”. So, we can find different kinds of anagram of a word.
Now, you are given two array S and T. You have to find a
lexicographically smallest
contiguous subsequence of S which is an anagram of array T.
Between two sequence A and B, where length(A) == length(B), A will be lexicographically smaller than B if we can find an index i (1<= i <= length(A)) where A[i] < B[i] and for all j, A[j] = B[j] where 1 <= j < i.
Input
The first line of the input is the number of the test cases Ts.
Each test case contains three lines. The first lines contains N and M, N is the length of array S and M is the length of array T.
Next line contains N integers of array S. Then another line follows containing M integers of array T.
Constraints
1 <= Ts <= 20
1 <= N, M <= 200000
1 <= S[i], T[i] <= 200000
Output
First you need to print the case number. Then on the same line, you have to print the index (1 based) of the lexicographically smallest contiguous subsequence of S which is an anagram of T. If there is more than one answer, you need to print the smallest index. If you can't find any anagram of the T in S, just print 0.
Sample
Input:
2
4 3
1 3 2 4
1 2 3
5 3
3 2 1 4 10
1 2 4
Output:
Case 1: 1
Case 2: 2 | 34,042 |
Secret Key (ICCSECRET)
You are working in security cell of your Institute Computer Center (ICC) and want to generate a secret key following a pattern. The pattern consists of the characters 'A' and 'B' where 'A' means increasing and 'B' means decreasing. Generate the secret key which is the minimum number encoded following that pattern.
Digits 1-9 in the key and digits can not repeat.
Input
Input starts with an integer T denoting the number of test cases.
T lines follows containing pattern string (length ≤ 8) consisting of 'A' and 'B' only.
Output
For every test case, output the minimum number denoting that pattern.
Example
Input:
2
AABBA
BBBA
Output:
125436
43215 | 34,043 |
Mr. Ant & His Problem (ANTP)
Mr. Ant has
3
boxes and the infinite number of marbles. Now he wants to know the number of ways he can put marbles in these three boxes when the following conditions hold.
Each box must contain at least 1 marble.
The summation of marbles of the 3 boxes must be in between X and Y inclusive.
Now you are given X and Y. You have to find the number of ways Mr. Ant can put marbles in the 3 boxes.
Input
Input starts with an integer T, denoting the number of test cases. Each test case contains two integers
X
and
Y.
Constraints
1 ≤ T ≤ 1000000
1 ≤ X ≤ Y ≤ 1000000
Output
For each test case, print the required answer modulo
1000000007
.
Example
Input:
1
4 5
Output:
9
Explanation for the first test case
1
1
2
Way 01
1
1
3
Way 02
1
2
1
Way 03
1
3
1
Way 04
2
1
1
Way 05
3
1
1
Way 06
1
2
2
Way 07
2
1
2
Way 08
2
2
1
Way 09
Note: use faster i/o method.
Problem Setter: Md Abdul Alim, Dept. of Computer Science, Bangladesh University of Business & Technology | 34,044 |
NO GCD (NGCD)
You are given
N (1 <= N <= 100000)
integers. Each integer is square free (meaning it has no divisor which is a square number except 1) and all the prime factors are less than 50. You have to find out the number of pairs are there such that their gcd is 1 or a prime number. Note that (i, j) and (j, i) are different pairs if i and j are different.
Input
The first line contains an integer
T (1 <= T <= 10)
, the number of tests. Then T tests follows. First line of each tests contain an integer
N
. The next line follows
N
integers.
Output
Print
T
lines. In each line print the required result.
Example
Input:
1
3
2 1 6
Output:
8
Explanation
gcd(1, 2) = 1
gcd(2, 1) = 1
gcd(2, 6) = 2, a prime number
gcd(6, 2) = 2, a prime number
gcd(1, 6) = 1
gcd(6, 1) = 1
gcd(2, 2) = 2, a prime number
gcd(1, 1) = 1
So, total of 8 pairs.
Problem Setter: Nafis Sadique, Jahangirnagar University | 34,045 |
Tiho Brdo (SHILL)
In the medieval ages, in the small town of Silent Hill lived a monster named Glutton, which loved terrorising the townsfolk. Many knights have tried to slay it, but none have been able to survive the encounter.
One day, a brave architect called Davis has decided to attack the Glutton. He found out that the monster actually consists of a bunch of
parts
, interconnected in such a way that each part may
control
other parts. The Glutton has exactly one part corresponding to its
brain
; a part not controlled by any other part. Furthermore, the Glutton may have one or more parts that do not control any other part---these correspond to its
claws
. For every claw there exists
exactly one set of connections
through which the brain (directly or indirectly) controls it. If Davis successfully manages to disconnect the brain from all the claws, the Glutton remains completely harmless.
Davis took advantage of his project skills in order to determine that one may assign a
power
w
xy
required to sever each of the Glutton's direct connections
x -> y
. Davis wishes to invest a
minimal total amount of power
in order to disconnect the brain from all the claws, therefore he is interested in knowing which connections,
left-to-right
, he needs to destroy in order to achieve this. If there are multiple appropriate solutions, Davis would prefer to have the invested power early on be as small as possible, i.e. he would like to know the
lexicographically smallest
appropriate solution.
Blinded by the fame he would attain and the folks' cheers of "Thank you, brave Davis!" should he defeat the Glutton, Davis is too impatient to compute the solution; he has asked you for help.
Input
The first line of the standard input contains an integer
n
, representing the number of the Glutton's parts. The part with ID 1 always represents the brain. Afterwards, a description of all the parts follows in order, starting from the brain, up to the part with ID
n
, in order, as follows:
The first line contains an integer
m
i
, representing the number of parts directly controlled by the current part.
If
m
i
= 0
holds, then the current part is a claw.
Otherwise, the second line will contain an array
a
of
m
i
integers, representing
the indices of the parts directly controlled by the current part,
left-to-right
.
The third line will then contain an array
w
of
m
i
integers, such that the
j
-th member of
w
,
w
j
, represents the power necessary to destroy the connection through which the current part controls the
j
-th member of
a
,
a
j
.
Output
Write to the first line of the standard output a single integer representing the minimal total power required for Davis to disable the Glutton. Then, the second line should contain the
lexicographically smallest
sequence of powers required for severing each of the individual connections, provided in a left-to-right order. Separate individual elements of the sequence with a single space.
Example
Input:
7
2
2 5
4 7
2
3 4
2 3
0
0
2
6 7
1 6
0
0
Output:
11
4 1 6
Explanation
The figures below represent the sample testcase; the left figure represents the Glutton's initial state as provided by the input, and the right figure represents the optimal solution. The brain is denoted by a black background, and the claws are denoted by a red outline. The crossed and dashed connections represent the ones that Davis should destroy. There are
two
solutions that require the total power of 11; they are, in a left-to-right order,
{4, 7}
and
{4, 1, 6}.
We choose the lexicographically smaller out of the two as the final solution.
Constraints
2 <=
n
<= 10
5
;
1 <=
w
j
<= 10
9
;
The total number of connections will always be
n - 1
, and for every claw there will exist a unique set of connections linking it to the brain. | 34,046 |
Stockade (STO)
The year is 50 B.C. Gaul is entirely occupied by the Romans. Well, not entirely! One small village of indomitable Gauls still holds out against the invaders. And life is not easy for the Roman legionaries who garrison the fortified camps of Totorum, Aquarium, Laudanum and Compendium...
The year is 49 B.C. Gaul is entirely occupied by the Romans. Well, no one could seriously expect one small village to resist the mighty army of the great Roman Empire. Fortunately, thanks to Julius Caesar's infinite generosity (
Ave Caesar!
), the settlement wasn't razed to the ground. There was no other choice for the villagers than to conform to the new authorities.
But some of the rules of Roman law can be downright ridiculous. As it turns out, even heights of individual stakes in the stockade encircling the village are strictly regulated. Here is an excerpt from the law, laid down by Roman clerks, and approved by the great ruler, Gaius Julius Caesar (
Ave Caesar!
):
Every stockade encircling every village in the whole Roman Empire (governed justly by the great Julius Caesar) should have even number of wooden logs.
Every log in every stockade should have some minimum height, specified in "Weights and Measures Act", article 15, passage 9. Moreover, the logs can be at most 1000 quarters of a sicilicus
1
higher than this minimum height.
For every log, the adjacent logs have to be both higher or both lower. It symbolizes the harmony in the whole Roman Empire, governed justly by the great Julius Caesar (
Ave Caesar!
).
1
sicilicus
- Roman unit of length, equal to 1/48 of Roman foot.
As one might expect, stockade around the village of indomitable Gauls did not meet the requirements - specifically, it violated the last rule (it did satisfy the first two, though). Now, the villagers have to lower or raise some of the logs, but this is a lot of work. Determine the minimum number of logs that have to be lowered or raised, so that the final stockade will satisfy the rule of harmony.
Input
The first line contains a single integer
t
, denoting the number of testcases. Then, testcases follow.
Each testcase consist of a single line. It begins with an integer
n
, indicating the number of logs in the stockade. (2 ≤
n
≤ 10
6
, 2 |
n
), followed by
n
integers
x
i
, indicating the difference between the height of the i-th log and the minimal possible height, expressed in quarters of a sicilicus (0 ≤
x
i
≤ 1000). i-th log is adjacent to (i+1)-th log, moreover, first log is adjacent to the last log (stockade encircles the village).
Output
For every testcase you should output one integer - minimum number of logs that have to be lowered or raised, so that the stockade satisfies the requirements of Roman law.
Example
Input:
3
6 1 2 3 4 5 6
6 1 2 1 2 1 2
6 2 2 2 2 2 2
Output:
2
0
3
Explanation
In the first case it is enough to lower the third and the fifth log to height 1. In the second case, the stockade already satisfies all the rules. (
Ave Caesar!
) | 34,047 |
Counter-Smack (COU)
Januarius the Clairvoyant recently started playing the popular, team-based online video game - Counter-Smack. His paranormal abilities are certainly a big help during the gameplay, but even having a keen inner eye is not enough when all of your teammates are total noobs. There's just no way to climb up the ranking when something like this happens.
Counter-Smack's ranking system is really simple. The player starts with zero points. For every win he gains a point, for every defeat he loses a point. Of course the more points, the better.
One may think that using the gift of clairvoyance you could detect the noobs in advance, and just skip the game in case they would join your team. Unfortunately, that's not how the laws of the universe work, and Januarius knows that. As it turns out, team-based online games are one of the few cases where the Primeval Law of Destiny applies - it may just so happen that you will be joined by noobs in the next game and you can't do anything about it, as it is already written down in the Universum's atoms.
Fortunately, there is a loophole. You can join the game and immediately leave, and the destiny will be fulfilled. Even though you lose a point for leaving the game (just as in the case of simply losing), you are additionally banned for a few next games - and being banned also fulfills the destiny.
Using his abilities, Januarius can predict the future for the next
n
games - he will know whether he will be joined by the noobs or not. When leaving the game for the first time, the player is banned for the next one. Leaving for the second time will get you banned for the next two games. Leaving for the third time results in a ban that lasts for four games, and so on - every ban is twice as long as the previous one.
What is the maximum number of points Januarius can achieve in
n
successive games, if he starts with zero points, he wins every match without the noobs on his team, and loses all the other matches?
Input
The first line contains a single integer
t
, denoting the number of test cases. Then t test cases follow, each in a separate line.
Each test case consists of a string of length
n
, describing the predicted future for the next
n
games. (1 ≤
n
≤ 2×10
5
). i-th letter indicates the i-th game. "N" means that Januarius will be joined by the noobs in this game, "P" denotes good players.
Output
For each test case you should output a single integer - the maximum number of ranking points that Januarius can achieve by abandoning some of the matches.
Example
Input:
4
PPPPP
PPPPN
NNPPP
NNNNN
Output:
5
3
2
-2
Explanation
In the third testcase, by abandoning the first game, Januarius will be banned for the next one. He will win the rest of them, so his final result will be (-1)+3 = 2 points.
In the fourth testcase, Januarius can abandon the first game, which will get him banned for the next one. Then he can abandon another game, and this time he will get banned for the last two games. His final score will be -2 points, for abandoning two games. | 34,048 |
Who is the Best? (INS16F)
Baratheon is one of the oldest houses in the Land of Seven Kingdoms. There have been many kings and their many heirs. The hierarchy is represented as a tree where each character is a node with initial value as the
Varys_Value
given by Lord Varys. You are the analyser appointed to the current King to give insights about a character.
There are
Q
commands given by the King which can be any of the following type:
1. Multiply the
Varys_Value
of all the characters in path from
u
to
v
by a given number
P.
2. For a given character
X
, find the number of
ordered pairs (i,j)
such that
LCM(i,j)
is equal to current value at node
X
. (Insight)
For commands of second type, print the number of such pairs (modulo
1000000007
).
Input
First line contains 2 space separated integers
N
and
Q
indicating the number of total characters and number of queries you need to answer.
In the next
N-1
lines, each line contains 2 integers
u
,
v
which indicates a relationship between character
u
and character
v
.
Next line contains
N
space separated integer
V
1
, V
2
, V
3
, ...... V
N
where
V
i
indicates the Varys_Value of
i
th
character.
Following
Q
lines contains the queries to be answered.
Types of Queries:
1 u v P
- Query of first type
2 X
- Query of second type
Output
For each query of second type, print the answer to the query in a new line.
Constraints
1 ≤ N ≤ 100000
1 ≤ Q ≤ 100000
1 ≤ u, v ≤ N
1 ≤ P ≤ 100
1 ≤ V
i
≤ 100000
Example
Sample Input:
6 6
1 2
4 6
1 3
5 1
4 5
7 8 4 8 1 2
1 2 1 14
2 4
1 6 5 10
2 5
1 6 4 10
2 1
Sample Output:
7
9
15 | 34,049 |
Daenerys wants to Conquer (INS16H)
With full zeal, Daenerys Targaryen is looking to conquer the seven kingdoms. In need of wise commanders, she wants them to solve the below problem:
Given the following function
F
and an integer
N
find the smallest integer
x
satisfying
F(x) = N
.
function f(x) {
ret = 0
for d = 1..x:
if (x mod d == 0) and
(gcd(d, x/d) == 1):
ret += d
return ret
}
If no such x exists, print “
-1
” (without quotes.)
Input
The first line contains one integer
T
, the number of times she gives you the problem.
T
lines follow, each containing a single integer
N
.
Output
Print the answer for each problem on a separate line.
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 10
10
Example
Input:
4
5
4
9
7
Output:
4
3
8
-1 | 34,050 |
Pristojba (PRISTOJBA)
In a galaxy far far away there is a new low-cost space carrier starting daily interplanetary flights. In the galaxy there are
N
planets, numbered with integers from 1 to
N
. Cost of a flight between two planets depends only on take-off/landing fees of those planets. For each planet
k
you are given his fee,
p
k
, so the cost of a flight between planets
a
and
b
is
p
a
+ p
b
.
Space carrier wants to determine the flights it will offer daily so that any planet can be reached from any other planet, directly or indirectly.
Because of space reasons it's possible to conduct flights only between certain pairs of planets. Allowed flights are described with
M
permissions of form "
x
k
a
k
b
k
" which means it's possible to conduct a bidirectional flight between planet
x
k
and any planet
c
, where
a
k
≤
c
≤
b
k
.
Find the minimum total cost of offered flights such that all planets are connected.
Input
N M
p
1
p
2
.. p
N
x
1
a
1
b
1
x
2
a
2
b
2
..
x
M
a
M
b
M
1 ≤ N, M ≤ 10
5
For each p
k
following holds: 0 ≤ p
k
≤ 10
6
.
For each permission it holds that either x
k
< a
k
or x
k
> b
k
.
Also, it's possible that some pairs of planets are listed in more than one permission.
It will always be possible to choose flights such that all planets are connected.
Output
Minimum daily cost of space carrier transportation system.
Example
Input:
6 8
3 5 8 2 9 4
3 1 2
6 3 3
3 1 1
6 2 2
2 3 6
3 1 2
3 2 2
4 1 1
Output:
46
Explanation: we connect following pairs of planets: (1, 3), (1, 4), (4, 2), (2, 5), (2, 6). | 34,051 |
SUPER CELL (SCELL)
Titania, the largest moon of Uranus. Recently a living cell has been found there and scientists say that this is the beginning of life there. They call it Super cell.
The super cell is very surprising. It lives for
T
seconds. Every second
K-mitosis
event occurs in the super cell. In a
K-mitosis
event,
K
new super cells born from the mother super cell. These new super cells also lives for exactly
T
seconds and
K-mitosis
event occurs every second in all the living super cells.
When the initial super cell has been found the time is 0 second. This super cell lives for next
T
seconds and at the
T
'th second it dies. Every super cell dies after
T
'th second when it is born.
You have to tell how many super cell will be there in Titania at
N
'th second.
Input
Input starts with an integer
TC
denoting number of test cases. In next
TC
lines there will be three integers
T
,
K
and
N
in each line.
T
denotes the amount of time a super cell lives.
K
denotes how many new super cells born during mitosis event.
N
denotes that you have to answer how many super cells live there in Titania at
N
'th second.
Output
For every test case print a single integer modulo 1000000007 (1e9+7), the number of super cells living at
N
'th second in Titania.
Constraints
1 ≤
TC
≤ 50
0 ≤
T
≤ 30
1 ≤
K
≤ 100
0 ≤
N
≤ 1000000000
Sample
Input
3
5 2 4
3 1 5
1 2 4
Output
81
24
16
Explanation
In the first sample:
At 0
th
second, 1 cell is there.
At 1
st
second, 2 new cells are born and there are total 3 living cells.
At 2
nd
second, 6 new cells are born and there are total 9 living cells.
At 3
rd
second, 18 new cells are born and there are total 27 living cells.
At 4
th
second, 54 new cells are born and there are total 81 living cells.
In the second sample:
At 0
th
second, 1 cell is there.
At 1
st
second, 1 new cell is born and there are total 2 living cells.
At 2
nd
second, 2 new cells are born and there are total 4 living cells.
At 3
rd
second, 4 new cells are born and the cell which is born at 0
th
second dies. So, there are total 7 living cells.
In the third sample:
At 0
th
second, 1 cell is there.
At 1
st
second, 2 new cells are born and the cell which is born at 0
th
second dies. So, there are 2 living cells.
At 2
nd
second, 4 new cells are born and the cells which are born at 1
st
second die. So, there are 4 living cells.
At 3
rd
second, 8 new cells are born and the cells which are born at 2
nd
second die. So, there are 8 living cells.
At 4
th
second, 16 new cells are born and the cells which are born at 3
rd
second die. So, there are 16 living cells. | 34,052 |
Collecting Mango (CMG)
One day after storm mina went to pick up mangoes in the garden with a basket. She began to pick up mangoes from the garden. And if she wants, she can throw away the last picked up mango from the basket. In this way, mina kept picking up mangoes. She brought you with her to keep track of the biggest size of mango in the basket at that time. At any moment Mina can ask you about the biggest size of mango. Your job is to help Mina.
Since you are a good programmer, so you write a program by which you are easily able to answer the question of Mina.
During picking up mangoes, Mina can have 3 types of question/instruction for you.
Type 1: put an ‘x’ size mango in the basket, which is picked up form garden.
Type 2: Throw out last picked up mango. (There can be consecutive throw out operation.)
Type 3: Ask for the biggest mango size in the basket at that moment.
Input
The first line contains a positive integer
T
, number of test case. In the following each case start with a positive integer N, which is number of question/operation Mina will ask during picking up mangoes. Next N lines will contain 3 types of operations (A, R, Q). A x, here x is picked up mango size. R, throw out last picked up mango from basket. Q Find out the biggest size mango.
Output
For each case, first print the case number and print the answer of Mina’s question. Whenever the basket is empty, then Mina’s question’s answer will be “Empty”.
Constraints
1 ≤ T ≤ 25
1 ≤ N ≤ 100000
1 ≤ x ≤ 100000
Example
Input:
2
6
A 10
A 5
Q
A 100
R
Q
6
A 5
Q
R
Q
R
R
Output:
Case 1:
10
10
Case 2:
5
Empty | 34,053 |
Extremely Lagged Fibonacci (EXLAGFIB)
Let $(\ a_i\ )_{i=0}^\infty$ be the integer sequence such that: $$a_n = \begin{cases} 0 & (0 \le n < k - 1) \\ 1 & (n = k - 1)\\ b \cdot a_{n-j} + c \cdot a_{n-k} & (n \ge k) \end{cases}, $$ where $j$, $k$, $b$ and $c$ are integers.
For each $n, j, k, b$ and $c$, find $a_n$
modulo
$1\,000\,000\,037$.
Input
The first line contains $T$, the number of test cases.
Each of the next $T$ lines contains five integers $n, j, k, b$ and $c$.
Output
For each test case, print $a_n$
modulo
$1\,000\,000\,037$.
Constraints
$1 \le T \le 10^2$
$0 \le n \le 10^9$
$10^5 \le k \le 10^8$, $1 \le j < k$
$1 \le b \le 10^9$, $1 \le c \le 10^9$
Example
Input:
2
1000000 1 100000 1 1
1000000000 1 100000000 1 1
Output:
372786243
994974348 | 34,054 |
The Crossover (CROSSOVER)
Scientist Aftab has made a groundbreaking discovery regarding chromosomal crossover today!
Before going into details let’s understand a few definitions first. According to Holland’s convention, a gene is represented by either 0 or 1. A chromosome is a string of genes. While in crossover, two parental chromosomes arbitrarily get separated at the exact same position forming four non-empty parts. And these parts join together to form two offspring. For example, let A and B be two parental chromosomes of length N. After cutting those at arbitrary position X, we get four parts LA, RA, LB, RB. Here LA is made of A[0,…,X], RA is made of A[X+1,…,N-1] and the same for LB and RB. After applying crossover, we get two offspring O1=LA+RB andO2= LB+RA. Here ‘+’ is string concatenation operator.
Scientist Aftab’s claim is that, the fittest offspring among O1 and O2 is the one which is greater in value. Here the value of a chromosome is computed keeping in mind that this is a bitstring with the leftmost bit being the Most Significant Bit (MSB) and the rightmost bit is the Least Significant Bit (LSB).
Although scientist Aftab is a great genetics researcher, he is not good at handling chromosomes of large size. So he is seeking your help. You will be given two chromosomes of length N. And you will have to output the decimal value modulo 10
9
+7 of the fittest offspring after applying crossover.
Input
Input starts with an integer
T(<=30)
, denoting the number of test cases. Each case contains two lines containing two strings of same length
N (2<=N<=100000)
. Strings will contain only 0’s and 1’s.
Output
For each case of input, print the case number followed by the decimal value modulo 10
9
+7 of the fittest string after the crossover.
Sample I/O
Input
Output
2
100101
110010
10010
11101
Case 1: 53
Case 2: 30
Explanation of Sample I/O
For the first case, the fittest offspring is 110101, whose decimal value modulo 10
9
+7 is 53. | 34,055 |
Game Of Ones (GOO)
Haba and Goba are brothers, they love binary numbers very much. Today is Haba’s birthday so, his uncle gifted him a 3 bit binary string. Getting the present, both of them are very happy. Now, Goba asked Haba that using 3 bits how many different binary numbers he can write, whose 1
st
bit is 1 and total how many 1 will be needed to write those numbers. Haba answered he can write 4 different numbers using 3 bits whose first bit is 1 and those numbers are 4 (100), 5 (101), 6 (110) and 7 (111) and to write these 4 numbers in binary he will need 8 ‘1’. Now Goba told Haba that he will tell Haba the length of a binary string n and Haba will have to answer that using n bits how many different binary numbers he can write, whose 1
st
bit is 1 and total how many 1 will be needed to write those numbers. If Haba can answer correctly he will get more binary strings as present. Haba wants to get more binary string as present but, he doesn’t know the answer of the question of Goba for bigger value of n, so now he wants your help. Help him to find the answer.
Input
The first line contains a positive integer number, t (1 ≤ t ≤ 50) indicating the number of test cases. Each test case contains a positive integer number, n (1 ≤ n ≤ 50) indicating the number of bits.
Output
For each test case you have to output two numbers, whose first and second number indicates the answer of Goba’s first and second question respectively.
Example
Input:
2
2
3
Output:
2 3
4 8 | 34,056 |
Kuchu the Bookworm (BOOKWORM)
In this problem, you’ll be helping a little bookworm, Kuchu.
Recently “Omuk book shop” has announced a huge sale on various books. Being a bookworm, Kuchu could not miss this opportunity and went there immediately!
When reached there, she noticed that conditions of the sale are:
One must buy exactly B books to get the discount.
Maximum number of pages in any book is no more than 100.
As she wants to read as much as possible, Kuchu wants to get maximum number of pages satisfying the conditions above. Now she is wondering if there are N books in the store, how many different ways are there to choose exactly B books so that the number of pages is maximum possible.
Not all books are interesting to little kids, so you are given two information about each book-
Number of pages P.
Interest value V. V is 1 if the book is interesting for kids and 0 otherwise.
Input
First line contains an integer T, the number of test cases.
For each test case, the first line contains two integers N and B as mentioned above. Next N lines contain two integers each P
i
and V
i
, number of pages and interest factor of ith book.
1 ≤ T ≤ 25
1 ≤ N ≤ 100,000
1 ≤ B ≤ N
1 ≤ P
i
≤ 100
0 ≤ V
i
≤ 1
Output
For each test case, print one integer, the number of different ways to choose exactly B
interesting books
from those N books so that the number of pages is maximum possible. As result can be pretty large, print it modulo
1,000,000,007 (10^9+7)
.
Example
Input:
2
2 1
2 0
3 0
5 3
10 0
5 1
2 1
2 1
2 1
Output:
0
3 | 34,057 |
k Alternating Sum (KALTSUM)
Sameen has:
An array having N integers,
Q friends.
His friends are curious about the array. So, each of his friends asks Sameen a question about the array. Every question is described by 3 integers: i, j and k. In reply to a question, Sameen has to say the “k alternating sum” of the subarray starting at position i and ending at position j [1 based indexing].
“k alternating sum” of a subarray starting at position i and ending at position j can be calculated in the following way:
Add the first k numbers [starting from position i]
Subtract the second k numbers [starting from position i+k]
Add the third k numbers [starting from position i+2*k]
Subtract the fourth k numbers [starting from position i+3*k]
And so on till adding/subtracting the j-th number…
(j-i+1) will be divisible by k.
[See sample Input/output and explanation section for more details]
Can you help Sameen in answering the questions?
Input
The first line of input contains two integers N and Q. The next line contains N integers, the numbers in the array. Then each of the following Q lines contains 3 integers i, j & k.
Output
For each query output an integer in a separate line, the answer for that query. Queries should be answered in the order given in the input.
Constraints:
1 ≤ k ≤ 100000
1 ≤ N ≤ 100000
1 ≤ Q ≤ 100000
-1000000000 ≤ Value of a number in the array ≤ 1000000000
(j-i+1) will be divisible by k
.
Example
Input:
6 6
4 1 -2 -3 4 5
2 5 2
1 6 1
1 6 3
1 6 6
3 3 1
3 4 1
Output:
-2
3
-3
9
-2
1
Explanation
In the first query, the subarray is [ 1, -2, -3, 4].
So “2 alternating sum” is equal to: [1-2]-[-3+4] = -2
For the second query, we get [4]-[1]+[-2]-[-3]+[4]-[5] = 3
N.B: Dataset is huge. Use faster I/O method. | 34,058 |
The Maximize Sum (TMSUM)
You are given a set S of n elements. Do you know how many subsets the set has? It is 2
n
where n is the number of elements in S.
For example, consider a set S of 3 elements. S = {1, 2, 3} so S has 2
3
= 8 subsets. They are {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}, { }. Here { } is empty set.
In the above example number of subsets of S having at most 2 elements excluding empty set are {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}.
Find subsets which have at most 2 elements excluding empty set in which each element of S must belong to a single a subset i.e. if we take subset for example {1} then we can’t take other subsets containing element 1. Now sum the product of the subsets containing 2 elements with the value of subsets containing single element. Your target will be maximizing this sum.
For example consider a set S= {1, 2, 3, 4, 5, 6}. So the subsets of S having at most 2 elements excluding the empty set are {1}, {2}, {3}, {4}, {5}, {6}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {3, 4}, {3, 5}, {3, 6}, {4, 5}, {4, 6}, {5, 6}.
Now we can take subsets of {5, 6}, {4, 3} and {1, 2} which contains all 6 elements of S then total sum will be = (5 * 6) + (4 * 3) + (1 * 2) = 44. On the other hand if we take subsets of {5, 6}, {4, 3} and {1} and {2} then total sum will be (5 * 6) + (4 * 3) + 1 + 2 = 45 which is greater than the previous one.
Input
The first line of the input will be an integer T to represent the number of test cases. For each case there will be two lines. The first line contains integer
n
— the number of distinct elements in the given set S. The second line contains
n
integers s
i
(i = 1, 2 ... n) — the elements of the S.
Output
In a single line, output the maximum sum.
Constraints
1 ≤ T ≤ 100
1 ≤ n ≤ 100
-10000 ≤ s
i
≤ 10000
Example
Input:
2
6
1 2 3 4 5 6
3
1 2 3
Output:
45
7 | 34,059 |
Spaceship (SPACESHIP)
In the future world, you have moved into the space colony, and will be using a flying disc which moves in three dimensions as a vehicle. You have been assigned with buying the parts to form 'N' sets of computer from the shops in the colony. Each set of computer consists of 3 parts: monitor, keyboard, and CPU. Because the parts available at one shop may not be enough for the 'N' computers and the budget is limited, you have to design a navigation system for the flying disc such that the total cost of navigation is minimized. You know the exact coordinates of the 'M' available shops and the number of the parts available at each store. Assume that the route from a shop to every other shop will have no obstacles, thus a straight path is always possible, the flying disc contains unlimited storage space, and the parts at each store are free. Let the trip terminate when all parts needed are collected.
Let shop/position A has coordinate (X1, Y1, Z1) and shop/position B has coordinate (X2, Y2, Z2), the navigation cost between the two shops/positions is calculated by the formula (X1-X2)^2 + (Y1-Y2)^2 + (Z1-Z2)^2.
Input
The first line contains the integer 'N': the number of the required sets of computer.
The second line contains three integers 'X', 'Y', 'Z': the initial position of the spaceship in the form of coordinates (X, Y, Z)
The third line contains the integer 'M': the total number of shops in the colony
There follows 2M lines: the information for each shop in the colony, where two lines are responsible for the information of one shop.
The first of these two lines contains three integers 'Xi', 'Yi', 'Zi', the position of the shop in the form of coordinates (X, Y, Z)
The second of these two lines contains three integers 'Mi', 'Ki', 'Ci', the number of monitors, keyboards, and CPUs, respectively, available at the shop.
It is guaranteed that it is sufficient to build 'N' sets of computers from all parts of every shop combined.
Output
One line containing the minimum navigation cost from the initial position to the end of the trip.
Constraints
1 <= 'N' <= 20
0 <= 'X', 'Y', 'Z', 'Xi', 'Yi', 'Zi' <= 500
1 <= 'M' <= 10
0 <= 'Mi', 'Ki', 'Ci' <= 20
Example
Input #1:
1
0 0 0
2
10 0 0
2 5 7
0 10 0
0 3 9
Output #1:
100
Input #2:
5
0 0 0
5
60 34 56
0 5 7
90 41 92
1 7 8
24 61 81
6 8 8
41 86 70
5 6 7
46 97 85
9 2 4
Output #2:
10542 | 34,060 |
Hofstadter–Conway 10000 dollar sequence (HC10000)
Hofstadter–Conway $10,000 sequence is a famous sequence, which is defined as $$ a_1 = a_2 = 1,\, a_{n} = a_{a_{n-1}} + a_{n-a_{n-1}}\, (n \ge 3). $$
Your task is to find a summatory function $S(n) := \sum\limits_{i=1}^n a_i$ and compute $S(n)$
modulo
$10^9$.
Input
The first line contains $T$ ($1 \le T \le 10000$), the number of test cases.
Each of the next $T$ lines contains a positive integer $n$ ($1 \le n \le 10^{18}$).
Output
For each test case, print $S(n)$
modulo
$10^9$.
Example
Input:
10
1
2
3
4
5
10
100
1000
1000000
1000000000
Output:
1
2
4
6
9
32
2818
269446
334706485
137951847
Explanation
You can verify that $a_1 = a_2 = 1$, $a_3 = a_4 = 2$ and $a_5 = 3$. So, $S(5) = 9$.
$S(10^9) = 259987670137951847 \equiv 137951847 \pmod{10^9}$.
Information
There are 5 input files:
- #1: $n \le 10^{4}$, TL = 2s.
- #2: $n \le 10^{6}$, TL = 2s.
- #3: $n \le 10^{8}$, TL = 3s.
- #4: $n \le 10^{12}$, TL = 5s.
- #5: $n \le 10^{18}$, TL = 12s.
These time limits allow a (slow) Python2 solution to get accepted. | 34,061 |
Shoot and kill (BGSHOOT)
The problem is about Mr. BG who is a great hunter. Today he has gone to a dense forest for hunting and killing animals.
Sadly, he has only one bullet in his gun. He wants to kill as many animals as possible with only one bullet.
He has already known the information of duration availability of all animals of the forest.
So, he is planning to shoot at a time so that he could kill maximum number of animals.
Input
Input begins with an integer
N
denoting total numbers of animals.
Next
N
lines contains the duration of availability of animal denoting by X (starting time) and Y (ending time) .
Then, there will be
Q
, denoting the total numbers of queries to be answer.
Each query giving two integer
L
and
R
,
L
denoting the time hunter will come to forest and begins shooting and
R
denoting last time up to which he will stay at forest for hunting.
Output
For each query output an integer denoting maximum numbers of animals he could kill by shooting at a time during L and R (inclusive).
Constraints
1<=N, Q<=100000
1<=X, Y, L, R<=1000000000
Example
Input:
4
1 2
2 3
4 5
6 7
4
1 5
2 3
4 7
5 7
Output:
2
2
1
1 | 34,062 |
Assembly line (EIUASSEMBLY)
The Alternate Control Machine (ACM) Factory has a large assembly line to make a type of product. The assembly has N robots (R
1
, R
2
... R
N
) working sequentially. That means a semi-finished product moves from robot R
1
, to R
2
, then to R
3
... to R
N
. Each robot adds a component to the product. Each robot can complete its own job in P
i
products per one hour.
The company has a budget of M VNĐ to improve productivity for the entire assembly. As a product director, you know that robot R
i
needs to invest M
i
VNĐ to contribute to the production of one more product per hour. You have to optimize the amount of money to invest to each robot to produce maximum number of products per hour.
Input
The first line of input contains one integer T (1 ≤ T ≤ 10) - the number of test cases.
Then T test cases are given as follows:
The first line of each test case contains an integer N (1 ≤ n ≤ 10
5
) and an integer M (0 ≤ M ≤ 10
12
) – the number of robots and the budget
Line i-th of the next N lines contains two integers P
i
(1 ≤ P
i
≤ 10
9
) and M
i
(1 ≤ M
i
≤ 10
9
) – information of the robot i-th
Output
For each test case, output in one line the maximum number of products the assembly can make after investing at most M VNĐ.
Example
Input:
1
3 7
1 2
2 3
3 1
Output:
3
Hint: You should check for the case: company budget is 0, or cannot upgrade any robot at all. This is the visualization explain why you should check if you use binary search to solve. | 34,063 |
Balanced Diet (FN16DIET)
Every day, Danny buys one sweet from the candy store and eats it. The store has $m$ types of sweets, numbered from $1$ to $m$. Danny knows that a balanced diet is important and is applying this concept to his sweet purchasing. To each sweet type $i$, he has assigned a
target fraction
, which is a real number $f_ i$ ( $0 < f_ i \le 1$). He wants the fraction of sweets of type $i$ among all sweets he has eaten to be roughly equal to $f_ i$. To be more precise, let $s_ i$ denote the number of sweets of type $i$ that Danny has eaten, and let $n = \sum _{i=1}^ m s_ i$. We say the set of sweets is
balanced
if for every $i$ we have
\[ n f_ i - 1 < s_ i < n f_ i + 1. \]
Danny has been buying and eating sweets for a while and during this entire time the set of sweets has been balanced. He is now wondering how many more sweets he can buy while still fulfilling this condition. Given the target fractions $f_ i$ and the sequence of sweets he has eaten so far, determine how many more sweets he can buy and eat so that at any time the set of sweets is balanced.
Input
The input consists of multiple test cases. Please process until EOF is reached.
Each test case consists of three lines. The first line contains two integers $m$ ($1 \le m \le 10^5$), which is the number of types of sweets, and $k$ ($0 \le k \le 10^5$), which is the number of sweets Danny has already eaten.
The second line contains $m$ positive integers $a_1, \ldots , a_ m$. These numbers are proportional to $f_1, \ldots , f_ m$, that is, $\displaystyle f_ i = \frac{a_ i}{\sum _{j = 1}^ m a_ j}$. It is guaranteed that the sum of all $a_ j$ is no larger than $10^5$.
The third line contains $k$ integers $b_1, \ldots , b_ k$ ( $1 \le b_ i \le m$), where each $b_ i$ denotes the type of sweet Danny bought and ate on the $i^\text {th}$ day. It is guaranteed that every prefix of this sequence (including the whole sequence) is balanced.
Output
For each test case, display the maximum number of additional sweets that Danny can buy and eat while keeping his diet continuously balanced. If there is no upper limit on the number of sweets, display the word
forever
.
Example
Input:
6 5
2 1 6 3 5 3
1 2 5 3 5
6 4
2 1 6 3 5 3
1 2 5 3
Output:
1
forever | 34,064 |
Branch Assignment (FN16ASGN)
The Innovative Consumer Products Company (ICPC) is planning to start a top-secret project. This project consists of $s$ subprojects. There will be $b \ge s$ branches of ICPC involved in this project and ICPC wants to assign each branch to one of the subprojects. In other words, the branches will form $s$ disjoint groups, with each group in charge of a subproject.
At the end of each month, each branch will send a message to every other branch in its group (a different message to each branch). ICPC has a particular protocol for its communications. Each branch $i$ has a secret key $k_ i$ known only to the branch and the ICPC headquarters. Assume branch $i$ wants to send a message to branch $j$. Branch $i$ encrypts its message with its key $k_ i$. A trusted courier picks up this message from this branch and delivers it to the ICPC headquarters. Headquarters decrypts the message with key $k_ i$ and re-encrypts it with key $k_ j$. The courier then delivers this newly encrypted message to branch $j$, which decrypts it with its own key $k_ j$. For security reasons, a courier can carry only one message at a time.
Given a road network and the locations of branches and the headquarters in this network, your task is to determine the minimum total distance that the couriers will need to travel to deliver all the end-of-month messages, over all possible assignments of branches to subprojects.
Input
Multiple test cases. Please process until EOF is reached. For each test case:
The first line of input contains four integers $n$, $b$, $s$, and $r$, where $n$ ($2 \le n \le 5\, 000$) is the number of intersections, $b$ ( $1 \le b \le n-1$) is the number of branches, $s$ ($1 \le s \le b$) is the number of subprojects, and $r$ ($1 \le r \le 50\, 000$) is the number of roads. The intersections are numbered from $1$ through $n$. The branches are at intersections $1$ through $b$, and the headquarters is at intersection $b + 1$. Each of the next $r$ lines contains three integers $u$, $v$, and $\ell $, indicating a one-way road from intersection $u$ to a different intersection $v$ ($1 \leq u,v \leq n$) of length $\ell $ ($0 \leq \ell \leq 10\, 000$). No ordered pair $(u,v)$ appears more than once, and from any intersection it is possible to reach every other intersection.
Output
For each test case, display the minimum total distance that the couriers will need to travel.
Example
Input:
5 4 2 10
5 2 1
2 5 1
3 5 5
4 5 0
1 5 1
2 3 1
3 2 5
2 4 5
2 1 1
3 4 2
5 4 2 10
5 2 1
2 5 1
3 5 5
4 5 10
1 5 1
2 3 1
3 2 5
2 4 5
2 1 1
3 4 2
Output:
13
24 | 34,065 |
Ceiling Function (FN16CEIL)
Advanced Ceiling Manufacturers (ACM) is analyzing the properties of its new series of Incredibly Collapse-Proof Ceilings (ICPCs). An ICPC consists of $n$ layers of material, each with a different value of collapse resistance (measured as a positive integer). The analysis ACM wants to run will take the collapse-resistance values of the layers, store them in a binary search tree, and check whether the shape of this tree in any way correlates with the quality of the whole construction. Because, well, why should it not?
To be precise, ACM takes the collapse-resistance values for the layers, ordered from the top layer to the bottom layer, and inserts them one-by-one into a tree. The rules for inserting a value $v$ are:
If the tree is empty, make $v$ the root of the tree.
If the tree is not empty, compare $v$ with the root of the tree. If $v$ is smaller, insert $v$ into the left subtree of the root, otherwise insert $v$ into the right subtree.
ACM has a set of ceiling prototypes it wants to analyze by trying to collapse them. It wants to take each group of ceiling prototypes that have trees of the same shape and analyze them together.
Given a set of prototypes, your task is to determine how many different tree shapes they induce.
Input
Multiple test cases. Please process until EOF is reached. For each test case:
The first line contains two integers $n$ ( $1 \le n \le 50$), which is the number of ceiling prototypes to analyze, and $k$ ($1 \le k \le 20$), which is the number of layers in each of the prototypes.
The next $n$ lines describe the ceiling prototypes. Each of these lines contains $k$ distinct integers (between $1$ and $10^6$, inclusive), which are the collapse-resistance values of the layers in a ceiling prototype, ordered from top to bottom.
Output
For each test case, display the number of different tree shapes.
Example
Input:
5 3
2 7 1
3 1 4
1 5 9
2 6 5
9 7 3
3 4
3 1 2 40000
3 4 2 1
33 42 17 23
Output:
4
2 | 34,066 |
Clock Breaking (FN16CLK)
After numerous unfortunate freak fatalities and the lawsuits, settlements, protests, and boycotts that naturally followed, the beleaguered executives at ACME Clock Manufacturers have decided they need to finally fix their disastrous quality control issues. It has been known for years that the digital clocks they manufacture have an unacceptably high ratio of faulty liquid-crystal display (LCD) screens, and yet these heartless souls have repeatedly failed to address the issue, or even warn their hapless consumers!
You have been called in as a quality consultant to finally put a stop to the madness. Your job is to write an automated program that can test a clock and find faults in its display.
These clocks use a standard 7-segment LCD display for all digits (shown in figure below), plus two small segments for the
:
, and show all times in a 24-hour format. The minute before midnight is 23:59, and midnight is 0:00. The
:
segments of a working clock are on at all times. The representation of each digit using the seven segments is shown below.
Your program will be given the display of a clock at several consecutive minutes, although you do not know exactly what time these displays start. Some of the LCD segments are burnt out (permanently off) and some are burnt in (permanently on). Your program must determine, where possible, which segments are definitely malfunctioning and which are definitely in working order.
Input
Multiple test cases. Please process until EOF is reached. For each test case:
The first input line contains a single integer $n$ ($1 \leq n \leq 100$), which is the number of consecutive minutes of a clock s display. The next $8n-1$ lines contain $n$ ASCII images of these clock displays of size $7 \times 21$. Every representation is followed by a blank line except the last one of each test case.
All digit segments are represented by two characters, and each colon segment is represented by one character. The character
X
indicates a segment that is on. The character
.
indicates anything else (segments that are off or non-segment portions of the display). See the sample input/output for details; the first output shows every possible LCD segment along with the smaller segments used to represent the
:
. No clock representation has an
X
in a non-segment position or only half of a segment showing.
Output
For each test case, display a $7 \times 21$ ASCII image with a
0
for every segment that is burnt out, a
1
for every segment that is burnt in, a
W
for every segment that is definitely working, and a
?
for every segment for which the status cannot be determined. Use
.
for non-segments. If the given displays cannot come from consecutive minutes, display
impossible
.
Example
Input:
3
......XX.....XX...XX.
.....X..X...X..X....X
.....X..X.X.X..X....X
.............XX...XX.
.....X..X......X.X..X
.....X..X......X.X..X
......XX.....XX...XX.
......XX.....XX...XX.
.....X..X...X..X....X
.....X..X.X.X..X....X
.............XX...XX.
.....X..X......X.X..X
.....X..X......X.X..X
......XX.....XX...XX.
.............XX...XX.
........X...X..X....X
........X.X.X..X....X
.............XX......
........X...X..X.X..X
........X...X..X.X..X
......XX.....XX...XX.
2
......XX.....XX...XX.
...X....X...X..X.X..X
...X....X.X.X..X.X..X
......XX..........XX.
...X.X....X.X..X.X..X
...X.X......X..X.X..X
......XX.....XX...XX.
......XX.....XX......
...X....X...X..X.....
...X....X.X.X..X.....
......XX.............
...X.X....X.X..X.....
...X.X......X..X.....
......XX.....XX......
Output:
.??...WW.....??...??.
?..?.W..?...?..1.0..?
?..?.W..?.?.?..1.0..?
.??...??.....11...WW.
?..?.W..?.0.W..?.1..?
?..?.W..?...W..?.1..?
.??...11.....??...??.
impossible | 34,067 |
Forever Young (FN16BASE)
My birthday is coming up. Alas, I am getting old and would like to feel young again. Fortunately, I have come up with an excellent way of feeling younger: if I write my age as a number in an appropriately chosen base $b$, then it appears to be smaller. For instance, suppose my age in base $10$ is $32$. Written in base $16$ it is only $20$!
However, I cannot choose an arbitrary base when doing this. If my age written in base $b$ contains digits other than $0$ to $9$, then it will be obvious that I am cheating, which defeats the purpose. In addition, if my age written in base $b$ is too small then it would again be obvious that I am cheating.
Given my age $y$ and a lower bound $\ell $ on how small I want my age to appear, find the largest base $b$ such that $y$ written in base $b$ contains only decimal digits, and is at least $\ell $ when interpreted as a number in base $10$.
Input
Multiple test cases. Please process until EOF is reached. Each test case consists of a single line containing two base 10 integers $y$ ( $10 \le y \le 10^{18}$ – yes, I am
very
old) and $\ell $ ($10 \le \ell \le y$).
Output
For each test case, display the largest base $b$ as described above in a single line.
Example
Input:
32 20
2016 100
Output:
16
42 | 34,068 |
Longest Rivers (FN16RIVER)
The Chao Phraya River System is the main river system of Thailand. Its six longest rivers listed by decreasing length are:
Tha Chin ($765$ km)
Nan ($740$ km)
Yom ($700$ km)
Ping ($658$ km)
Pa Sak ($513$ km)
Wang ($335$ km)
A simplified model of this river system is shown in figure below, where the smaller red numbers indicate the lengths of various sections of each river. The point where two or more rivers meet as they flow downstream is called a
confluence
. Confluences are labeled with the larger black numbers. In this model, each river either ends at a confluence or flows into the sea, which is labeled with the special confluence number $0$. When two or more rivers meet at a confluence (other than confluence $0$), the resulting merged river takes the name of one of those rivers. For example, the Ping and the Wang meet at confluence $1$ with the resulting merged river retaining the name Ping. With this naming, the Ping has length $658$ km while the Wang is only $335$ km. If instead the merged river had been named Wang, then the length of the Wang would be $688$ km while the length of the Ping would be only $305$ km.
The raised awareness of this phenomenon causes bitter rivalries among the towns along the rivers. For example, the townspeople along the Wang protest that maybe with a proper naming scheme, their river could actually be the longest, or maybe the second longest (or at least not last!). To end all the guessing, your task is to validate all such claims.
The
rank
of a river is its position in a list of all rivers ordered by decreasing length, where the best rank is $1$ for the longest river. For each river, determine its best possible rank over all naming schemes. At any confluence, the name of a new, larger river in any naming scheme must be one of the names of the smaller rivers which join at that confluence. If two or more rivers have equal lengths in a naming scheme, all the tied rivers are considered to have the best possible ranking. For example, if one river is the longest and all other rivers are equal, those rivers all have rank $2$.
Input
The first line of input contains two integers $n$ $(1 \le n \le 500\, 000)$, which is the number of river sources in the system, and $m$ $(0 \le m \le n - 1)$, which is the number of confluences with positive labels. These confluences are numbered from $1$ to $m$.
The next $n$ lines describe the rivers. Each of these lines consists of two integers $c$ $(0 \leq c \leq m)$ and $d$ $(1 \leq d \leq 10^9)$, where $c$ is the identifier of the nearest confluence downstream, and $d$ is the distance from the source to that confluence in kilometers.
The final $m$ lines describe confluences $1$ to $m$ in a similar fashion. The $k^\text {th}$ of these lines describes the confluence with identifier $k$ and contains two integers: the identifier of the nearest confluence downstream and the distance from confluence $k$ to this confluence in kilometers.
It is guaranteed that each confluence $1$ through $m$ appears as “the nearest downstream” at least twice, confluence $0$ appears at least once, and all sources are connected to confluence $0$.
Due to the input file size limit, all numbers given in the input file is written in base 64 integers. Base 64 integer uses 0-9 to denote number 0 - 9, A-Z to denote number 10 - 35, a-z to denote number 36 - 61, + to denote number 62 and / to denote number 63.
Output
Display one river per line in the same order as in the input. On that line, display the river's best possible rank (in decimal notation).
Example
Input:
6 2
0 81
2 AZ
2 Ay
1 5F
1 4n
0 Bz
0 5X
0 11
Output:
5
2
1
3
4
1
Input:
6 3
1 GN
2 fQ
1 CW
3 B6
0 h/
3 CJ
2 1a
0 Qa
0 U
Output:
1
1
3
6
1
4 | 34,069 |
Oil (FN16OIL)
A large part of the world economy depends on oil, which is why research into new methods for finding and extracting oil is still active. Profits of oil companies depend in part on how efficiently they can drill for oil. The International Crude Petroleum Consortium (ICPC) hopes that extensive computer simulations will make it easier to determine how to drill oil wells in the best possible way.
Drilling oil wells optimally is getting harder each day – the newly discovered oil deposits often do not form a single body, but are split into many parts. The ICPC is currently concerned with stratified deposits, as illustrated below.
To simplify its analysis, the ICPC considers only the 2-dimensional case, where oil deposits are modeled as horizontal line segments parallel to the earth’s surface. The ICPC wants to know how to place a single oil well to extract the maximum amount of oil. The oil well is drilled from the surface along a straight line and can extract oil from all deposits that it intersects on its way down, even if the intersection is at an endpoint of a deposit. One such well is shown as a dashed line in Figure, hitting three deposits. In this simple model the amount of oil contained in a deposit is equal to the width of the deposit. Can you help the ICPC determine the maximum amount of oil that can be extracted by a single well?
Input
Multiple test cases. Please process until EOF is reached. For each test case:
The first line of input contains a single integer $n$ ( $1 \leq n \leq 2\, 000$), which is the number of oil deposits. This is followed by $n$ lines, each describing a single deposit. These lines contain three integers $x_0$, $x_1$, and $y$ giving the deposit’s position as the line segment with endpoints $(x_0,y)$ and $(x_1,y)$. These numbers satisfy $|x_0|, |x_1| \leq 10^6$ and $1 \le y \le 10^6$. No two deposits will intersect, not even at a point.
Output
For each test case, display the maximum amount of oil that can be extracted by a single oil well.
Example
Input:
5
100 180 20
30 60 30
70 110 40
10 40 50
0 80 70
3
50 60 10
-42 -42 20
25 0 10
Output:
200
25 | 34,070 |
Road Times (FN16ROAD)
Ubol Narongdid is the founder of a brash new startup company called Special D-Liver-E. She wants to corner the market on overnight deliveries of organs between hospitals in the Phuket area. For scheduling purposes it is important to have accurate estimates for the times to perform such deliveries. Several trips between various hospitals have already been performed, so delivery times between those pairs of hospitals are known. The company currently has software to estimate times for other (as yet untraveled) trips, but so far all the estimates have been woefully inaccurate.
You have been asked to come up with a method to improve these estimates. You have at your disposal the following information: 1) the length (in kilometers) of the roads connecting each pair of cities in the Phuket area, and 2) a set of times (in minutes) for various previously executed deliveries.
You know that roads are one-way, and each road has a fixed speed limit that lies between $30$ and $60$ kilometers per hour. Speed limits are real-valued and need not be integers. You also know that delivery trucks always take the route that minimizes distance traveled, and on each road will always travel at a constant speed equal to that road’s speed limit. Thus you know, for example, that if a given trip is $50$ kilometers, the time it will take is between $50$ and $100$ minutes inclusive, in the absence of any other information. Ah, but you
do
have other information, namely the times of previous deliveries. It is up to you to use it to produce the best possible estimates.
Input
Multiple test cases. Please process until EOF is reached. For each test case:
The input starts with a line containing an integer $n$ ( $1 \le n \leq 30$) indicating the number of cities, numbered $0$ to $n-1$. After that are $n$ lines each containing $n$ integers specifying the distance in kilometers between cities: the $j^{\text {th}}$ value on the $i^{\text {th}}$ line indicates the distance when traveling directly from city $i$ to city $j$. A value of $-1$ indicates there is no road directly connecting the two cities, and the distance from any city to itself is always $0$; all other distances are positive and at most $1\, 000$. There are at most $100$ roads.
Following this is a line with a single integer $r$ ($1 \le r \leq 100$) indicating the number of previously executed routes. The next $r$ lines each contain three integers $s$, $d$, and $t$, where $s$ and $d$ are the source and destination cities and $t$ is how long the delivery from $s$ to $d$ took, in minutes.
Finally there is a line containing a single integer $q$ ( $1 \le q \leq 100$) indicating the number of future delivery queries. The next $q$ lines each contain two integers $s$ and $d$ giving the source and destination cities for the query.
You may assume that for each of the $r+q$ source/destination pairs in the input there is a unique minimum-distance route.
Output
For each test case, display a single line for each query containing the source and destination cities for that query, followed by the best low and high bounds on the estimate for the travel time.
The judge is "ignore FP Rounding up to $10^{-2}$".
Example
Input:
3
0 50 -1
55 0 40
-1 40 0
1
0 2 120
3
0 1
1 2
1 0
Output:
0 1 50.0 80.0
1 2 40.0 70.0
1 0 55.0 110.0 | 34,071 |
String Theory (FN16QUOT)
Nested quotations are great not only for writing literature
with a complex narrative structure, but also in programming
languages. While it may seem necessary to use different
quotation marks at different nesting levels for clarity, there
is an alternative. We can display various nesting levels using
$k$-quotations, which are
defined as follows.
A $1$-quotation is a
string that begins with a quote character, ends with another
quote character and contains no quote characters in-between.
These are just the usual (unnested) quotations. For example,
'this is a string'
is a
$1$-quotation.
For $k > 1$, a
$k$-quotation is a string
that begins with $k$ quote
characters, ends with another
$k$ quote characters and contains a
nested string in-between. The nested string is a non-empty
sequence of
$(k-1)$-quotations, which may
be preceded, separated, and/or succeeded by any number of
non-quote characters. For example,
''All
'work' and no 'play'''
is a
$2$-quotation.
Given a description of a string, you must determine its
maximum possible nesting level.
Input
Multiple test cases. Please process until EOF is reached. For each test case:
The input consists of two lines. The first line contains an
integer $n$ (
$1 \le n \le 100$). The second line
contains $n$ integers
$a_1, a_2, \ldots , a_ n$
($1 \le a_ i \le 100$),
which describe a string as follows. The string starts with
$a_1$ quote characters,
which are followed by a positive number of non-quote
characters, which are followed by
$a_2$ quote characters, which are
followed by a positive number of non-quote characters, and so
on, until the string ends with
$a_ n$ quote characters.
Output
For each test case, display the largest number
$k$ such that a string described by
the input is a
$k$-quotation. If there is no such
$k$, display
no quotation
instead.
Example
Input:
5
2 1 1 1 3
1
22
1
1
Output:
2
4
no quotation | 34,072 |
Swap Space (FN16SWAP)
You administer a large cluster of computers with hard drives that use various file system types to store data. You recently decided to unify the file systems to the same type. That is quite a challenge since all the drives are currently in use, all of them are filled with important data to the limits of their capacities, and you cannot afford to lose any of the data. Moreover, reformatting a drive to use a new file system may significantly change the drive’s capacity. To make the reformat possible, you will have to buy an extra hard drive. Obviously, you want to save money by minimizing the size of such extra storage.
You can reformat the drives in any order. Prior to reformatting a drive, you must move all data from that drive to one or more other drives, splitting the data if necessary. After a drive is reformatted, you can immediately start using it to store data from other drives. It is not necessary to put all the data on the same drives they originally started on – in fact, this might even be impossible if some of the drives have smaller capacity with the new file system. It is also allowed for some data to end up on the extra drive.
As an example, suppose you have four drives $A$, $B$, $C$, and $D$ with drive capacities $6$, $1$, $3$, and $3$ GB. Under the new file system, the capacities become $6$, $7$, $5$, and $5$ GB, respectively. If you buy only $1$ GB of extra space, you can move the data from drive $B$ there and then reformat drive $B$. Now you have $7$ GB free on drive $B$, so you can move the $6$ GB from drive $A$ there and reformat drive $A$. Finally, you move the six total gigabytes from drives $C$ and $D$ to drive $A$, and reformat $C$ and $D$.
Input
Multiple test cases, please process until EOF is reached. For each test case:
The input begins with a line containing one integer $n$ ( $1 \le n \le 10^6$), which is the number of drives in your cluster. Following this are $n$ lines, each describing a drive as two integers $a$ and $b$, where $a$ is the capacity with the old file system and $b$ is the capacity with the new file system.
All capacities are given in gigabytes and satisfy $1 \le a,b \le 10^9$. (One thousand petabytes should be enough for everyone, right?)
Output
For each test case, display the total extra capacity in gigabytes you must buy to reformat the drives.
Example
Input:
4
6 6
1 7
3 5
3 5
4
2 2
3 3
5 1
5 10
Output:
1
5 | 34,073 |
What Really Happened on Mars? (FN16MARS)
Real-time software in the Mars Pathfinder spacecraft suffered from an issue known as priority inversion. One technique to address this issue is to use the Priority Ceiling Protocol.
In this problem, you will simulate the execution of multiple tasks according to this protocol. The tasks share a collection of resources, each of which can be used by only one task at a time. To ensure this, resources must be locked before use and unlocked after use. Each task is defined by a start time, a unique
base priority
, and a sequence of instructions. Each task also has a
current priority
, which may change during execution. Instructions come in three types:
compute
– perform a computation for one microsecond
lock $k$
– lock resource $k$ (which takes no processor time)
unlock $k$
– unlock resource $k$ (which takes no processor time)
After locking a resource, a task is said to
own
the resource until the task unlocks it. A task will unlock only the owned resource it most recently locked, will not lock a resource it already owns, and will complete with no owned resources.
Each resource has a fixed
priority ceiling
, which is the highest base priority of any task that contains an instruction to lock that resource.
There is a single processor that executes the tasks. When the processor starts, it initializes its clock to zero and then runs an infinite loop with the following steps:
Step 1.
Identify
running
tasks. A task is running if its start time is less than or equal to the current processor clock and not all of its instructions have been executed.
Step 2.
Determine the current priorities of the running tasks and which of the running tasks are
blocked
. A running task $T$ is blocked if the next instruction in $T$ is to lock resource $k$ and either resource $k$ is already owned or at least one other task owns a resource $\ell $ whose priority ceiling is greater than or equal to the current priority of $T$. If $T$ is blocked, it is said to be blocked by every task owning such $k$ or $\ell $. The current priority of a task $T$ is the maximum of $T$’s base priority and the current priorities of all tasks that $T$ blocks.
Step 3.
Execute the next instruction of the non-blocked running task (if any) with the highest current priority. If there was no such task or if a compute instruction was executed, increment the processor clock by one microsecond. If a lock or unlock instruction was executed, do not increment the clock.
The Priority Ceiling Protocol defined above has the following properties:
Current priority is defined in terms of current priority and blocking, and blocking is defined in terms of current priority. While this may appear circular, there will always be a unique set of current priorities that satisfy the definitions.
All tasks will eventually complete.
There will never be a tie in step 3.
Input
Multiple test cases. Please process until EOF is reached. For each test case:
The first line of the input contains two integers $t$ $(1 \leq t \leq 20)$, which is the number of tasks, and $r$ ($1 \leq r \leq 20$), which is the number of resources. This is followed by $t$ lines, where the $i^\text {th}$ of these lines describes task $i$. The description of a task begins with three integers: the task’s start time $s$ ($1 \leq s \leq 10\, 000$), its base priority $b$ ($1 \leq b \leq t$), and an integer $a$ ($1 \leq a \leq 100$). A task description is concluded by a sequence of $a$ strings describing the instructions. Each string is a letter (
C
or
L
or
U
) followed by an integer. The string
C
$n$ ($1 \leq n \leq 100$) indicates a sequence of $n$ compute instructions. The strings
L
$k$ and
U
$k$ ($1 \leq k \leq r$) indicate instructions locking and unlocking resource $k$ respectively.
No two tasks have the same base priority.
Output
For each test case:
For each task, display the time it completes execution, in the same order that the tasks are given in the input.
Example
Input:
3 1
50 2 5 C1 L1 C1 U1 C1
1 1 5 C1 L1 C100 U1 C1
70 3 1 C1
3 3
5 3 5 C1 L1 C1 U1 C1
3 2 9 C1 L2 C1 L3 C1 U3 C1 U2 C1
1 1 9 C1 L3 C3 L2 C1 U2 C1 U3 C1
Output:
106
107
71
8
15
16 | 34,074 |
Summer Trip (IAPCR2F)
In this hot summer AIUB students decided to go on a trip to Cox’s Bazaar sea beach. Every student has some amount of money to spend in this trip. Each student belongs to some group. If student A knows student B, B knows C then A, B and C belong to the same group. In order to utilize the budget properly students hired a travel agency to get an optimal travel plan. They submitted the information about all the student’s money and relations among them. Now the agency wants to figure out the number of groups and the total budget of each group. Total budget of a group is the summation of all the student’s money in that group.
Input
The first line contains an integer T (1 ≤ T ≤ 50), denoting the number of test cases.
Each case starts with two integers N M. N (1 ≤ N ≤ 1000), denotes the number of students and M (0 ≤ M ≤ (N×(N-1)/2)), denotes the number of relationships. In the next line N integers are given. The ith (1 ≤ i ≤ N) integer a
i
(1 ≤ a
i
≤ 100) denotes the money ith student has. Next M lines each contains two integers u v, (1 ≤ u, v ≤ N and u ≠ v) denoting that u knows v and vice versa.
Output
For each test case output “Case X: K” where X is the case number starting from 1 and K is the number of groups. In the next line output K integers, the total budget of all the groups in ascending order of budget.
Example
Input:
1
5 3
5 7 4 6 8
1 2
1 3
4 5
Output:
Case 1: 2
14 16 | 34,075 |
Find The Number (IAPCR2D)
Finding the number of all divisor of a number is too easy. But don’t worry, this problem is also quite easy.
You will be given the number of all divisor of the factorial of a number, you will have to find number. If there are multiple such number, you will have to find the smallest one. If there is no such numbers that meets the constraint print “nai”.
Input
The first line of the input will be T, denoting number of test cases. In the following T lines there will be only one integer N, denoting the number of all divisor of the factorial of a number X. It is guaranteed that X will be less than 10^2 + 10.
Constraints
1 <= t <= 10^5
0 <= n <= 10^18
1 <= X < 10^2 + 10
Output
For each test case print the number X. If X does not exists or is greater than 10^4 then print "nai" (without the quotes) in a single line. Follow the sample input/output.
Example
Input:
5
1
2
3
4
5
Output:
1
2
nai
3
nai | 34,076 |
Study Room (IAPCR2C)
In an algorithm lab class of Aiub there are N number of students and personal computer. All of the computers are arranged in one row. Due to some reason some of the computer are not working properly so students who have good computer are sharing their computer with their adjacent student means a student can only go to one step to his left or right.
You know the number of properly working computer and their position. Print maximum number of student who can use computer.
Input
The first line contains T (1 ≤ T ≤ 60) — the number of test cases.
The first line of each test case contains integer n (1 ≤ n ≤ 10
5
) — the number of student and m (1 ≤ m ≤ n) — properly working computer. The second line contains m integers b
i
(1 ≤ b
i
≤ n) position of ith properly working computer.
Output
Print maximum number of student who can use computer.
Example
Input:
2
6 2
2 5
5 2
2 5
Output:
Case 1: 6
Case 2: 5 | 34,077 |
Ballons Revisited (IAPCR2E)
You have w white, r red, g green and b blue balloons. To make a single student happy you need exactly four balloons. All four balloons given to a student shouldn't have the same color. What is the maximum number S of happy students if we know number of balloons of each color?
Your task is to write a program that for given values w, r, g and b will find the S.
Input
Input starts with an integer T (≤ 20000), denoting the number of test cases.
Each test case contains four integers w, r, g and b (0 ≤ w, r, g, b ≤ 10^9) — the number of white, red, green and blue balloons respectively. The numbers are separated by exactly one space.
Output
For each test case print a single integer S — maximum number of happy students.
Example
Input:
2
2 2 1 3
1 1 4 1
Output:
Case 1: 2
Case 2: 1 | 34,078 |
Periodic function, trip 5 (PERIOD5)
Solar cycle predictions are used by various agencies and many industry groups.
The solar cycle is important for determining the lifetime of satellites in low-Earth orbit,
as the drag on the satellites correlates with the solar cycle [...].
(NOAA)
(Solar Cycle)
Sunspot Number Progression : Observed data through May 2008 ; Dec 2012 ; Nov 2014 ; Jun 2016
The goal of the problem is to propose a perfect prediction center, with not so weak constraints.
Let us consider periodic functions from
Z
to
R
.
def
f
(x):
return
[
4
,
-
6
,
7
][x
%
3
]
# (with Python notations)
# 4, -6, 7, 4, -6, 7, 4, -6, 7, 4, -6, 7, 4, -6, 7, ...
For example,
f
is a 3-periodic function, with
f
(0) =
f
(3) =
f
(6) =
f
(9) = 4.
With a simplified notation we will denote f as [4, -6, 7].
For two periodic functions (with integral period), the quotient of periods will be rational, in that case it can be shown that the sum of the functions is also a periodic function. Thus, the set of all such functions is a vector space over
R
.
For that problem, we consider a function that is the sum of several periodic functions all with as period an integer
N
at maximum. You will be given some starting values, you'll have to find new ones.
Input
On the first line, you will be given an integer
N
.
On the second line, you will be given integers
y
: the first (0-indexed)
N×N
values of a periodic function
f
that is sum of periodic functions all with as period an integer
N
at maximum.
On the third line, you will be given
N×N
integers
x
.
Output
Print
f(x)
for all required
x
. See sample for details.
Example
Input:
3
15 3 17 2 16 4 15 3 17
10 100 1000 10000 100000 1000000 10000000 100000000 1000000000
Output:
16 16 16 16 16 16 16 16 16
Explanation
For example
f
can be seen as the sum of three periodic functions : [10] + [5, -8] + [0, 1, 2] (with simplified notations ; periods are 1,2 and 3)
In that case
f
(10) = [10][10%1] + [5, -8][10%2] + [0, 1, 2][10%3] = 10 + 5 + 1 = 16, and so on.
Constraints
N < 258
abs(y) < 10^9
0 <= x < 10^9
For PERIOD4 you can have AC with
O
(
N
⁶) method, for PERIOD3 the awaited solution is about π⁶/27 faster.
For PERIOD5 a new complexity is awaited.
Informations
You can safely assume output fit in a signed 32bit container.
There's 6 input files, with increasing value of
N
.
My modest C code ended in 1.27s ; no optimization.
Some details (#i,
N
, TL, t) :
(#0, around 50, 1s, 0s),
(#1, around 50, 1s, 0s),
(#2, around 100, 1s, 0.04s),
(#3, around 150, 3s, 0.14s),
(#4, around 200, 7s, 0.36s),
(#5, around 250, 15s, 0.74s).
You may first try the medium edition
PERIOD3
.
Have fun ;-)
(Edit 2017-02-11 ; compiler update ; here ×2 speedup) Some updated details (#i,
N
, TL, t) :
(#0, around 50, 1s, 0s),
(#1, around 50, 1s, 0s),
(#2, around 100, 1s, 0.02s),
(#3, around 150, 3s, 0.07s),
(#4, around 200, 7s, 0.18s),
(#5, around 250, 15s, 0.36s). | 34,079 |
Minimum Sum (SQRMINSUM)
Suppose you have a list of integers, and a
move
is defined as taking one of the integers from the list and replacing it with its square root, rounded down to the nearest integer.
Given an integer
l
and an integer
k
, start with the array
[1, 2, 3 ... l]
and find the minimal sum of the array after
k
moves
.
Example
For
l = 5
and
k = 2
, the output should be
squareRoots(l, k) = 10
.
We start with
[1, 2, 3, 4, 5]
.
After square rooting
5
to get
[1, 2, 3, 4, 2]
and then square rooting
3
to get
[1, 2, 1, 4, 2]
, we end up with a sum of
10
.
Constraints
1 ≤ l ≤ 10
4
1 ≤ k ≤ 10
4
T = 10000
Input
The first line contains T the number of test cases followed by 2×T lines containing l and k.
Output
For every test case, output one line containing an integer, i.e. the minimal possible sum.
Sample
Input:
2
5
2
2327
4895
Output:
10
10647 | 34,080 |
Segmentation (HJB)
Bobs just got an array A of
n
integers from his mother Ksenxi. She asked him to calculate the goodness of A.
Let's define f(a, b) of A as minimum value on interval [a, b] in A. Goodness of A is the number of pairs of segments [a, b], [c, d] such that
1
≤ a ≤ b < c ≤ d ≤
n
and f(a, b) ≤ f(c, d).
Since Bobs is writing an essay on matura in a few days he is now reading short summaries of books on the mandatory reading list so he needs your help to answer this hard question to his mom.
Input
The first line of the input contains an integer
n
(
1
≤
n
≤
500000
).
The second line contains n space-separated integers A
1
, A
2
... A
n
(
0
≤ A
i
≤
10
9
) - the array elements.
Output
Print out a single integer - the goodness of A. As the answer can be quite a large number, you should print it modulo
10
9
+ 7
(
1000000007
).
Example
Input:
5
5 3 0 9 8
Output:
21 | 34,081 |
Time for Revenge (MOWGLI)
Mowgli is a little boy brought up by a wolf pack in the jungle. The king of jungle Shere Khan wants the boy for revenge. Foreseeing his danger Akela the leader of wolf pack suggests Mowgli to leave the jungle. Before Mowgli's departure from jungle, he got the news that Shere Khan killed Akela. So Mowgli wants revenge. He wants to get back to Shere Khan's palace in shortest path.
There are
N
number of rivers in his path. Width of each river is at most
10
5
meters. To cross the river stones are kept at a distance of
1
meter. Mowgli can jump across at most
K
stones at a time. Given total number of stones
A
i
kept on the
i
th
river. Your job is to tell total number of ways Mowgli can cross each river. As answer can be very large, give output
modulo 1000000007
.
Input
There are around 10 test cases.
First line contains an integer
T
number of test cases
Each test case consists of two lines:
First line contains two integers
N (number of rivers)
and
K (maximum number of stones Mowgli can skip)
.
Next line contains
N
integers,
A
i
(number of stones kept on i
th
river)
.
Output
One line for each river.
Total number of ways Mowgli can cross the river.
Constraints:
T ≤ 10
1 ≤ N ≤ 100
0 ≤ K ≤ 50
0 ≤ A
i
≤ 100000
Example
Input:
1
2 1
1 2
Output:
2
3
Explanation
For second river with 2 stones. Mowgli can jump across 1 stone maximum at a time. So there are three choices
Start → 1st → 2nd → Destination.
Start → 1st → Destination.
Start → 2nd → Destination. | 34,082 |
Knight Move (KNMOVE)
Daniel is a chess player. At his free time, he usually plays chess with his family or his friends. But, sometimes they have their own activities, so Daniel can't play chess. He spends his time to learn about knight's move. He has 1,000 x 1,000 chessboard, numbered from 1 to 1,000. He wants to move his knight from (a, b) to (1, 1) with minimum movement. Help Daniel to solve it.
Input
The input file consists of several lines.
The first line contains a single number t representing the number of question Daniel asked. [ 1 <= t <= 1,000 ]
The next t lines contains a and b representing knight's position on the chessboard. [ 1 <= a, b <= 1,000 ]
Output
The output file should contains t lines.
The i-th line should contain one number – the minimum number of knight's movement.
Example
Input:
2
3 5
7 4
Output:
2
3 | 34,083 |
Sums of 2 and 3 (ORDSUM23)
Changu and Mangu are brothers. Changu likes 2 and Mangu likes 3. They decided to express each number as sum of 2 and 3.
They need your help. They want you to tell them the number of ways of writing a number as ordered sums of 2 and/or 3.
For example, there are 4 ways to write 8 as an ordered sum of 2s and/or 3s:
2 + 2 + 2 + 2
2 + 3 + 3
3 + 2 + 3
3 + 3 + 2
Input
The first line contains T, the number of test cases. It is followed by T lines, each containing the number N.
Output
You have to print the number of ways of writing N as ordered sum of 2 and/or 3. You have to print the answer mod 1000000007.
Example
Input:
3
2
3
8
Output:
1
1
4
Constraints:
T ≤ 100000
1 ≤ N ≤ 1000000 | 34,084 |
Funny Modular Sequence (FUNMODSEQ)
Lets define a funny modular sequence as a sequence such that:
a
1
x a
2
= 1 (mod p)
a
2
x a
3
= 1 (mod p)
...
a
n-1
x a
n
= 1 (mod p)
Also, a
1
, a
2
, a
3
... a
n
must be less than p and greater than or equal to 0. Given one element, a
1
, find the sum of the entire funny modular sequence of length n. If, for any a
i
, where i>=1, there exists no a
i+1
such that a
i
x a
i+1
= 1 (mod p), output -1.
Note
: p is not necessarily prime.
Input
The first line contains T, the number of test cases. T lines follow, each containing a
1
, p, and n.
Output
For each test case, output one line, the required sum.
Constraints
1<=T<=10
5
1<=a
1
<=10
5
1<=n<=10
9
a
1
< p <=10
9
Sample
Input:
2
2 3 2
3 7 2
Output:
4
8
Explanation
In the first test case, the funny modular sequence will be 2, 2, which has a sum of 4.
In the second test case, it will be 3, 5, which has a sum of 8. | 34,085 |
Matrices with XOR property (VECTAR1)
Imagine A is a NxM matrix with two basic properties
Each element in the matrix is distinct and lies in the range of 1<=A[i][j]<=(N*M)
For any two cells of the matrix, (i1,j1) and (i2,j2), if (i1^j1) > (i2^j2) then A[i1][j1] > A[i2][j2], where
1 ≤ i1, i2 ≤ N
1 ≤ j1, j2 ≤ M.
^ is bitwise XOR
Given N and M, you have to calculate the total number of matrices of size N x M which have both the properties mentioned above.
Input
First line contains T, the number of test cases. 2*T lines follow with N on the first line and M on the second, representing the number of rows and columns respectively.
Output
Output the total number of such matrices of size N x M. Since, this answer can be large, output it modulo 10^9+7
Constraints
1 ≤ N, M, T ≤ 1000
Sample
Input
1
2
2
Output
4
Explanation
The four possible matrices are:
[1 3] | [2 3] | [1 4] | [2 4]
[4 2] | [4 1] | [3 2] | [3 1] | 34,086 |
Changus Final Battle (VECTAR4)
Try the tutorial version first :
Changus Big Battle
: http://www.spoj.com/problems/VECTAR2/
Changu is going to fight a battle. He is powerful but he has a few limitations. If he kills x enemies on a particular day, then he can only kill x-1 or x or x+1 enemies on the next day. And also, he can kill no more than 1 enemy on the last day of battle. Given N, the number of enemies he has to kill to end the battle, you have to calculate the minimum number of days required for Changu to finish the battle, keeping in mind his limitations.
He starts on day 1 by x=1, i.e. killing one enemy.
Input
The first line contains an integer T denoting the number of test cases.
Each of the next T lines contain an integer N.
Output
T lines : Minimum number of days required for each test case.
Constraints
1 <= T <= 10^5
1 <= N <= 10^18
Example
Input:
3
4
1
9
Output:
3
1
5
Explanation
Case 1 : 1 + 2 + 1
Case 2 : 1
Case 3 : 1 + 2 + 3 + 2 + 1
Note: Test files have been updated. Solutions will be rejudged. | 34,087 |
Count Subsets (VECTAR5)
You are given a set S = {1, 2, 3 ... n}. Your task is simple. You have to calculate the number of ways of selecting non empty subsets A and B such that A is not a subset of B and B is not a subset of A. Since answer can be large output the result mod 10
9
+ 7.
Input
First line of input contains single integer t denoting number of test cases.
Next t lines contain a single integer n.
Output
For each test case output answer to problem by taking mod with 10
9
+ 7.
Constraints
1 ≤ t ≤ 100000
1 ≤ n ≤ 1000000
Example
INPUT:
2
4
8
OUTPUT:
110
52670 | 34,088 |
Cube Numbers (CUBNUM)
For any positive integer n, n can be represented as sum of other positive cube numbers (n = a
1
3
+ a
2
3
+ ... + a
m
3
).
Your task is to print the smallest m, where m is number of cube numbers used to form n, such that n = a
1
3
+ a
2
3
+ ... + a
m
3
.
For example:
n = 5, n = 1
3
+ 1
3
+ 1
3
+ 1
3
+ 1
3
(m = 5)
n = 8, n = 2
3
(m = 1)
n = 35, n = 2
3
+ 3
3
(m = 2)
Note: My fastest time is 0.09s :).
Edit: My fastest time is 0.05s now lol
My Java solution is also accepted.
Input
Input consists of several test cases separated by new lines. Each test case consists of a positive integer, denoting the number of n (1 ≤ n ≤ 10
5
). Input is terminated by end of file (EOF).
It is guaranteed that total test case per input file is less than 10
5
.
Note: For c++ users, you can use while(scanf("%d",&n)!=EOF); to read input until EOF.
Warning: large Input/Output data, be careful with certain languages!.
Output
For each case, print "Case #X: M", where X (1 ≤ X ≤ 10
5
) is the case number, and M is the minimum cube numbers used to form the integer n. There must be no trailing spaces at the end of printed lines, neither empty characters. Print a newline after each testcase.
Example
Input:
1
2
5
8
35
Output:
Case #1: 1
Case #2: 2
Case #3: 5
Case #4: 1
Case #5: 2 | 34,089 |
2D arrays with XOR property (XORRAY)
We consider 2D arrays $A$, (0,0)-indexed, shape $N \times M$.
With $ 0 \le i < N $ and $ 0 \le j < M $, we have $ 0< A_{i,j} \le N \times M $.
Our interest will be to count those arrays that have the two properties :
Arrays $A$ are composed with
all
numbers from $1$ to $N \times M$.
i.e. we have $ (i,j) \neq (k,l) \implies A_{i,j} \neq A_{k,l} $
$(i\oplus j) > (k\oplus l) \implies A_{i,j} > A_{k,l} $, where $ \oplus $ denotes bitwise XOR.
Input
The first line contains $T$, the number of test cases, and $P$ a prime number.
Each of the next $T$ lines contains $N$ and $M$, the shape of the arrays $A$.
Output
For each test case, print the number of arrays $A$ with the given properties.
As the result may be large, the answer
modulo
$P$ is required.
Example
Input:
2 1000000007
2 2
997 799
Output:
4
828630475
For the first case, the 4 possible 2x2 arrays are :
$ \binom{1\; 3}{4\; 2}$, $\binom{1\; 4}{3\; 2}$, $\binom{2\; 3}{4\; 1}$, and $\binom{2\; 4}{3\; 1}$.
Constraints
$1 \le T \le 10^4$,
$10^9 < P < 2\times 10^9$, a prime number,
$1 \le N \le 10^9$,
$1 \le M \le 10^5$.
Constraints allow a small kB of unoptimized PY3.4 code to get AC in the third of the TL.
Have fun. | 34,090 |
Count Doubles (CNTDO)
You are given an array of integers. Your task will be to determine how many integers in the array are twice of some other integers in the same array. For example, consider an array:
1 3 4 7 9 2 18
Here answer is 3 as 2 is twice of 1, 4 is twice of 2 and 18 is twice of 9.
Input
The first line of the input will be an integer T (T ≤ 1000) to represent the number of test cases. Each test case will contain two lines. The first line contains integer N (1 ≤ N ≤ 1000) which indicates the number of distinct integers in the given array. The second line contains N integers and each integer will not be greater than 10000 by its absolute value.
Output
In a single line, output the count of the integers that are double of some other integer.
Example
Input:
2
7
1 3 4 7 9 2 18
3
1 4 3
Output:
3
0 | 34,091 |
Alternating Sequences (ALTSEQ)
Given an array a of N integers a1, a2, a3, ... aN you have to find the longest alternating sub-sequence of this array.
An alternating sequence b1, b2 ... bk, k>=1 is a sequence that has the 2 following properties:
|b1| < |b2| < |b3| < ... < |bk|
The signs alternate between adjacent elements, i.e., if b1 > 0 then b2 < 0, b3 > 0 and so on. Alternatively, if b1 < 0, then b2 > 0, b3 < 0 and so on.
A sub sequence of array a is a sequence obtained by dropping some elements of the array a. Here is the formal definition.
It is guaranteed that the array a contains no element equal to 0.
Constraints
1 ≤ N ≤ 5000
|ai| ≤ 10
9
, ai not equal to 0.
Input
The first line contains a single integer N, denoting the size of the array. The next line contains N integers, denoting the array a.
Output
Print a single integer - the length of the longest alternating sub-sequence.
Example
Input:
8
1 2 -2 -3 5 -7 -8 10
Output:
5
Explanation
One of the longest alternating subsequence is
1 -2 5 -7 10 | 34,092 |
One more weird game (OMWG)
Leha is playing a very interesting game. The game will be played on a rectangular grid consisting of
N
rows and
M
columns. Initially all the cells of the grid are uncolored.
Leha's initial score is zero. At each turn, he chooses some cell that is yet not colored, and colors that cell. The score obtained in this step will be number of neighboring colored cells of the cell that Leha colored in this step. Two cells are neighbors of each other if they share a side between them. The game will end when all the cells are colored. Finally, total score obtained at the end of the game will sum of score obtained in each turn.
Leha wants to know what maximum score he can get? Can you please help him in finding this out?
Input
The first line contains a single integer T denoting the number of test cases. T test cases follow.
Each of the following T lines contains two space-separated integers N, M denoting the dimensions of the grid.
Output
For each test case, output a single line containing an integer corresponding to the maximal possible score Leha can obtain.
Constraints
1 ≤ T ≤ 100
0 ≤ N, M ≤ 1 000
Example
Input:
1
2 2
Output:
4
Explanation
Leha can obtain total score 4 in the following way.
In the first step, he colors down left cell, all the neighboring cells of this cell are uncolored. So, it adds 0 to total score.
In second step, he can color upper right cell, it also adds total 0 to the score.
In third step, he can color top left cell. There are two neighboring cell of this cell, both of which are colored. So, this add 2 to the score.
In the last step, he can choose the remaining down right cell. There are two neighboring cell of this cell, both of which are colored. So, this also add 2 to the score.
Leha can't obtain a score more than 4. Hence 4 is the answer. | 34,093 |
Number of Binary Trees (VECTAR6)
Changu has to deal with a very simple problem. He has to find the number of binary trees of height
n
where for each node the left subtree is at least as high as the right subtree.
NOTE
: The height of the binary tree here is in terms of the nodes, i.e, number of nodes in the path from the root to the deepest leaf node. Hence, the height of a tree with only root node is 1.
Input
The first line contains
T
, the number of test cases. The following
T
lines contain a number
N
.
Output
For each
N
output the number of binary trees of height
N
where for each node the left subtree is at least as high as the right subtree. As the answer can be large, you have to print answer modulus 1000000007
Example
Input:
2
1
2
Output:
1
2
Constraints
T
= 100000
1 <=
N
<= 10000000 | 34,094 |
Number of score sequences (VECTAR7)
Changu and Mangu were playing volleyball when they were handed a very easy question about the game. You can help them solve it.
In volleyball 2 teams play with initial score 0 and each team gets points which increases their scores by 1.
The game ends when: one of the teams gets 25 points and another team has < 24 points (strictly less than 24). If the score ties at 24:24, the teams continue to play until the absolute difference between the scores is 2.
Given the final score of a game (A B) i.e., the first team has scored A points and the second has scored B points, You have to find the number of different sequences of getting points by teams that leads to this final score?
Input
The first line contains the number of test cases T. The next T lines contain two integers A and B.
Output
Output the number of different sequences of getting points by the teams that leads to the final score A : B.
Final
means that the game should be over after this score is reached. If the number is larger than 10
9
+ 7, output the number modulo 10
9
+ 7. Print 0 if no such volleyball game ends with the given score.
Example
Input:
2
3 25
24 17
Output:
2925
0
Constraints
T <= 15
0 ≤ A, B ≤ 10
9
. | 34,095 |
Primal Fear (VECTAR8)
Changu and Mangu are afraid of prime numbers, but they are not afraid of all prime numbers. They were afraid of only a special kind of prime numbers. They are afraid of the prime numbers (without the digit zero, they love all the primes which have digits 0 in them) that remain prime no matter how many of the leading digits are omitted. For example, they are afraid of 4632647 because it doesn't have the digit 0 and each of its truncations (632647, 32647, 2647, 647, 47, and 7) are primes.
You are given a simple task, given a number of N, find out the number of primes not greater that N, that Changu and Mangu are afraid of.
Input
The first line contains T, the number of test cases. T lines follow, each containing a number N.
Output
On each line print the number of primes not greater that N, that Changu and Mangu are afraid of.
Example
Input:
3
2
3
4
Output:
1
2
2
Constraints
T ≤ 10
5
1 ≤ N < 10
6 | 34,096 |
Mangu Numbers (VECTAR9)
When Changu was introduced to the concept of prime numbers, he was so glad that, after one days happy work, he was able to generate the first thirteen prime numbers. He has the ability that, given any number, he can tell whether or not it is divisible by any of the first thirteen primes. The first thirteen prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, and 41; their product is 304250263527210. A number is called 'mangu' if it is divisible by at least one of the first thirteen primes. Thus, the first number that is not 'mangu' is 1, and the second is 43. Changu wrote all the 'mangu' numbers in ascending order in a list.
Your task is to find out, given k, what is the k-th element in the list.
Input
The first line contains T (not more than 500), the number of test cases. In each case there is a single number k.
Output
For each test case, output the k-th mangu number on a single line. You may assume that the answer is never bigger than 304250263527210.
Example
Input:
2
2
3
Output:
3
4 | 34,097 |
Card Game (VECTAR10)
Changu and Mangu have an ordered deck of
n
cards numbered 1 to
n
with card 1 at the top and card
n
at the bottom. They want to play a game. They perform a wierd operation as long as there are at least two cards in the deck: Changu throws away the top card and then Mangu moves the card that is now on the top of the deck to the bottom of the deck. Your task is to find the last remaining card.
Input
Each line of input (except the last) contains a positive number
n
≤ 1000000. The last line contains 0 and this line should not be processed. Input will not contain more than 500000 lines.
Output
For each number from input produce one line of output giving the last remaining card.
Example
Sample Input:
2
3
4
0
Sample Output:
2
2
4
Warning:
Large I/O data, be careful with certain languages | 34,098 |
Increasing numbers (NDS)
Subham and Dewang both are playing with numbers. Subham gives Dewang an array of numbers and asks him to tell the minimum possible last number of a increasing sequence of length
L
.
Note:
Check the sample I/O for more clarity.
Input
Input consists of number of test cases
T
. Each test case contains size of array i.e
N
. Next line contains
N
space separated elements of array. Next line contains length of the increasing sequence i.e.
L
.
Constraignts
1 ≤ T ≤ 100
0 ≤ N ≤ 10
6
0 ≤ a[i] ≤ 10
6
Output
You have to print the minimum possible last number of a sequence and if their is no increasing sequence of length
L
, then print "-1" without the quotes.
Example
Input:
1
7
9 7 2 5 4 11 12
3
Output:
11
Explanation
In sample input, possible increasing sequences of length L = 3 are (9, 11, 12), (7, 11, 12), (2, 5, 11), (2, 4, 11), (2, 5, 12), (2, 4, 12), (2, 11, 12), (5, 11, 12), (4, 11, 12) and the minimum last number is 11 for the sequences (2, 5, 11) and (2, 4, 11). Hence, the answer is 11. | 34,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.