task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Prismata (PRISMATA)
Mariusz and Pawel are playing a Prismata game. After many turns the situation is as follows. Pawel has:
one Gauss Fabricator, with
f
h
health, which will produce one Gauss Cannon per turn for the next
f
l
turns
g
Gauss Cannons, each Gauss Cannon has
g
h
health
Mariusz has
t
Tarsiers. Each Tarsier has one health. The Gauss Cannon and the Tarsier are the units with one attack. This means that the unit inflicts one damage per turn on a one of the opponent's units. A unit that has lost all its health is immediately destroyed. A unit which has only lost part of its health remains fully operational.
A single turn in Prismata goes like below:
Mariusz attacks. Mariusz decides how many Tarsiers attack the Gauss Fabricator and how many attack the Gauss Cannons. The same Gauss Cannon can be attacked by more than one Tarsier.
Pawel attacks. If Pawel has
n
Gauss Cannons, then Pawel destroys
n
Mariusz's Tarsiers (Pawel does not make any decisions).
If the Gauss Fabricator has not yet been destroyed, then it produces one Gauss Cannon with
g
h
health. Independently of the remaining health, the Gauss Fabricator is destroyed after producing
f
l
Gauss Cannons. Pawel can start attacking with the new Gauss Cannon in the next turn.
The player who destroys all the opponent's units wins.
Your task is to help Mariusz to find out whether he can win the game and calculate the minimum number of turns needed for the victory.
Input
The first line contains the number of tests
T (1 ≤ T ≤ 10)
. Each of the
T
next lines contains one test. A single test consists of:
f
h
(1 ≤ f
h
≤ 1000000)
- the health of the Gauss Fabricator
f
l
(1 ≤ f
l
≤ 1000000)
- the maximum number of Gauss Cannons produced by the Gauss Fabricator
g
h
(1 ≤ g
h
≤ 1000)
- the health of a single Gauss Cannon
g (0 ≤ g ≤ 1000000)
- the initial number of Gauss Cannons
t (1 ≤ t ≤1000000)
- the initial number of Tarsiers
Output
For each test your program should output:
"PAWEL" if Mariusz is unable to win the game
"MARIUSZ t" if Mariusz can win the game and
t
is the minimum number of turns needed for the victory
Example
Input:
3
5 100 2 5 7
100 3 10 0 8
100 1 60 0 10
Output:
MARIUSZ 4
MARIUSZ 6
PAWEL
Explanation of the sample tests
Test 1
: If left alone, the Gauss Fabricator will produce too many cannons. Therefore Mariusz has to destroy it. One of the possible way for Mariusz to win is:
Turn #1: Mariusz: 7 Tarsiers, Pawel: 5 Gauss Cannons (each with 2 health), the Gauss Fabricator has 5 health
Mariusz destroys 3 cannons and inflicts one damage on one of the remaining cannons.
Pawel has 2 cannons. He destroys 2 Tarsiers.
The Gauss Fabricator produces one cannon.
Turn #2: Mariusz: 5 Tarsiers, Pawel: 3 Gauss Cannons (2 Gauss Cannons with 2 health, one Gauss Cannon with 1 health), the Gauss Fabricator has 5 health
Mariusz destroys all 3 cannons.
Pawel hasn't got any cannons, all Tarsiers remain.
The Gauss Fabricator produces one cannon.
Turn #3: Mariusz: 5 Tarsiers, Pawel: 1 Gauss Cannon with 2 health, the Gauss Fabricator has 5 health
Mariusz destroys one cannon and inflicts 3 damage on the Gauss Fabricator.
Pawel hasn't got any cannons, all Tarsiers remain.
The Gauss Fabricator produces one cannon.
Turn #4: Mariusz: 5 Tarsiers, Pawel: 1 Gauss Cannon with 2 health, the Gauss Fabricator has 2 health
Mariusz destroys one cannon and the Gauss Fabricator.
Test 2
: In this test the Gauss Fabricator has a lot of health but will produce only few cannons. Mariusz should attack only the cannons and wait for the Gauss Fabricator to be destroyed after 3 turns.
Test 3
: Even though the Gauss Fabricator will produce only one cannon, the health of this cannon is too high for Mariusz to win. | 34,500 |
New Data Type (NDT)
Little boy maze invented a brand new data type that can store data from 1 to M inclusive. The specialty of the invented data type is if you want to store a data out of the range it can round the data and map with invented data type.
for example if the range is 1 to 7 and you want to store 9 then the system round 9 and map with 2.
Now you're given a number in the format A
B
and the upper limit M of range. Can you round the number to map with new data type?
Input
Input starts with T ≤ 100000.
in the next T lines there will be three integers (1 ≤ A, B ≤ 1000000000000000000, 1 < M < 1000000000).
Output
For each case print the desire output.
Example
Input:
2
2 3 5
4 2 15
Output:
3
1 | 34,501 |
Square Free Number (SFN)
A Square free number is a number whose sum of every adjacent two digits is not a perfect square and doesn't contain digit 0. For example, 123 is a square free number cause sum of first two adjacent digits 1 + 2 = 3 is not a perfect square and sum of last two adjacent digits 2 + 3 = 5 is not a perfect square.
You are given an integer n. You have to calculate the number of n-digit square free number.
As the result can be very big, output the result modulo 1000000007 (1e9 + 7).
Input
First line of the input contains a number T, the number of test cases.
Each of the next T lines will contain an integer n.
Output
Output the number of square free numbers of length n.
Constraints
T <= 1000.
1 <= n <= 10
18
.
Example
Input:
3
1
2
3
Output:
6
67
501
Note: By definition 1, 4, 9 is not square free number. | 34,502 |
Power Play (BAPPP)
As we are a “CricketPagol” (loves cricket a lot) nation , we know a lot about Cricket. So Mr. GoodForNothing , a fan of great cricketer Mashrafee think to develop an app that can found an interesting error in the game by visual effect. We all know about power play. Power play is the name for fielding restriction. Suppose, here are the rules of power play in ODI:
During P-1 (1 to 10 overs) maximum of 2 fielders are allowed outside the inner circle.
During P-2 (11 to 40 overs) maximum of 4 fielders are allowed outside the inner circle.
During P-3 (41 to 50 overs) maximum of 3 fielders are allowed outside the inner circle.
You know, there are two circles in the ground. We know that you are a programmer. So, you don’t have to develop the app. For simplifying the problem, you will be given the number of running over. And many pair of cricketer which denotes that they are in the same circle. You have to write a program that will identify that is there error occurs in fielder configuration or not? And we also give you the name of the wicket keeper.
Note that the wicket keeper is always in inner circle. And there can be eleven different cricketer names always.
Input
The first line contains two integer n (1 ≤ n ≤ 50) and m (10 ≤ m ≤ 50) which denotes that n
th
over is running now and number of pair of cricketer in the same circle respectively.
The second line contains the name of the wicket keeper.
The next m lines contain m pair of name of the cricketers.
Output
Print “Error” if there are error in fielder configuration. And print “No Error” otherwise.
Example
Input:
3 12
Mushfique
Mashrafee Sakib
Sakib Mushfique
Mashrafee Mushfique
Mashrafee Taijul
Taijul Mahmudullah
Taijul Rubel
Mahmudullah Mustafiz
Liton Imrul
Rubel Mustafiz
Liton Anamul
Mustafiz Tamim
Tamim Sakib
Output:
Error | 34,503 |
Machine Cooling (MACHCOOL)
Duck is a busy guy who has
N
tasks to do in a single day. The i-th task is scheduled at the
D
i
second starting from 00:00:00, for example, 65 is 00:01:05 and 82800 is 23:00:00. He recently bought
M
machines to help him complete the tasks automatically. Machines are very powerful that they can complete a task in 0 second, or you can say each machine can complete unlimited number of tasks scheduled at the same second.
"Unused machine is wasted machine", so Duck wants to use exactly M machines to complete all tasks. However, he also wants to maximize the cooling time of each machine whenever it completes a task, in order to make it more durable. Given that the maximum cooling time of each machine is 86400, no matters at what second a machine completes a task, but the cooling time must be the same for all machines. What is the maximum cooling time that every machine can have if you distribute all machines optimally?
Input
The first line is the number of test cases
T
. (1 ≤ T ≤ 50)
For each test case, it starts with the number of tasks
N
and the number of machines
M
. (1 ≤ N ≤ 100, 1 ≤ M ≤ N)
The next line has N integers,
D
i
is the second counting from 00:00:00 that the i-th task is scheduled at. (0 ≤ D
i
≤ 86399)
Output
Output the maximum cooling time that every machine can have.
Example
Input:
4
14 8
20 450 1 23605 1002 80727 5360 30000 623 40000 623 8888 959 902
6 6
9328 2018 80012 5840 33333 1024
3 2
727 727 727
8 2
2400 201 65003 73099 123 86399 86399 79821
Output:
5359
86400
0
2277
Explanation
In case 1, we can distribute the i-th machines responsible for different tasks as follows:
[1, 5360, 23605, 80727], [20, 8888, 30000, 40000], [450], [1002], [623], [623], [959], [902].
And now the maximum cooling time of each machine is 5359, 8886, 86400, 86400, 86400, 86400, 86400 and 86400 respectively, hence for all machines the answer is 5359.
In case 2, one machine for one task and both can have the cooling time of 86400.
In case 3, one machine for [727, 727] and another for [727], we then have the cooling time of 0 and 86400, hence the final answer is 0.
In case 4, we can have [123, 2400, 65003, 86399] and [201, 73099, 79821, 86399], we choose 2277 from 2277 and 6578. | 34,504 |
Plant the potatoes (POTATOPL)
You have a sack of
n
potatoes and a strip of land
(
n
+ 1) ⋅
k
centimeters long.
You want to evenly plant the potatoes on this strip. If we mark the beginning of the strip as centimeter
0
, then you want to plant the first potato at centimeter
k
, plant the second potato at centimeter
2
k
,
...
, plant the
n
-th potato at centimeter
n
k
(and then the strip of land ends at
(
n
+ 1) ⋅
k
centimeters).
Each potato has a growth range
r
i
. This means that if you plant the potato at centimeter
x
, and it has enough space, it will grow you some new tasty potatoes all across
[
x
−
r
i
,
x
+
r
i
]
.
However, a potato will never grow over another potato's growth territory, or beyond your strip of land - in other words, if the potato comes across the edge of the plot or bumps into a different potato plant, it stops growing in that direction.
Given
n
,
k
and
r
i
of your
n
potatoes, how many potatoes can you grow if you plant them optimally?
Input
The first line contains an integer
1 ≤
T
≤ 20
- the number of test cases.
T
test cases follow.
For each test case:
The first line contains the integers
1 ≤
n
≤ 10
6
and
1 ≤
k
≤ 10
9
. The second line contains
n
integers
1 ≤
r
i
≤
k
- the growth radii of the potatoes.
The sum of
n
within an input file will never exceed
2 ⋅ 10
6
.
Output
For each test case, output a single integer: the maximum length of strip you can cover in grown potatoes.
Examples
Input
3
3 20
6 12 4
3 20
12 12 12
3 5
1 1 5
Output
44
64
13
In the first case, if we plant the potatoes in the same order as in the input, that is 6->20cm, 12->40cm, 4->60cm, they will grow on [14,26], [28,52], [56,64] for a total of 12+24+8 = 44 cm of potatoes. Any other order works just as well, though.
In the second case we don't really have much to choose from.. The potatoes would want to grow out to [8,32], [28,52], [48,72], but they get in each other's way. So they will end up growing on [8,30], [30,50], [50,72] for a total of 64cm.
In the last case the best order to plant the potatoes is, for example, 5 1 1
. | 34,505 |
Rightful Distribution (SK_001)
Akash , the director of the famous Timus Coaching Institute was very happy after the results of the Entrance Examination, and decided to distribute sweets to the students according to their test scores. He shall distribute sweets according to the following conditions:
Every student must get at least one sweet.
A student with higher score gets more number of sweets than all students who scored less than him.
Help Akash to find out the minimum number of sweets that need to be distributed. Since the answer can be very large output it modulo 10
9
+ 7.
Input
The input consists of 3 lines. The first line contains T (1<=T<=10) denoting the number of test cases. The second line consists of a single integer N (1 <= N <= 10
5
) denoting the number of students.
The next line consists of N space separated integers a
1
, a
2
, a
3
... a
n
where a
i
denotes the test score of the i
th
student (0 <= a
i
<= 10
9
).
Output
Output a single integer denoting the minimum number of sweets to be distributed by Akash.
Example
Input:
2
2
1 2
3
100 200 50
Output:
3
6 | 34,506 |
Ono at the river 1 (ONORIVER1)
Oňo the grasshopper wants to cross the river. But the river is very wide –
w
meters from one bank to the other, and Oňo can only jump up to
d
meters at once. Fortunately, there are
n
lily pads growing in the river. They’re not big enough yet, but once they are adult, they will be able to hold Oňo’s weight.
The
i
-th lily pad is located
m
i
meters away from the left bank, where Oňo is right now. It will become able to support Oňo
s
i
seconds from now. But
e
i
seconds from now it will become too old and die.
Oňo is very fast and he can perform multiple jumps (each up to
d
meters) in a single second – every jump is practically instant. But he is still nervous. If he doesn’t plan things through, he could end up jumping across some lily pads only to find out there is no way forward, and now the lily pads behind him are gone and he can’t even get back! Oh, the horror! To prevent this, Oňo will only jump across the lily pads when he can immediately get from one side of the river to the other without stopping.
It would be great if someone wrote a program telling him at what time he can do so, and the total time that the river is crossable.
Task
Each lily pad has a time
s
i
when it turns adult and a time
e
i
when it dies; it can hold Oňo from the
s
i
-th to the
e
i
-th second. The lily pad is located
m
i
meters from the left bank of the river.
Find the earliest time that Oňo can cross the river without stopping, and also how many seconds there are such that he is able to do so.
Note that Oňo is not brave enough to jump from a lily pad which grows old at time
t
to a lily pad which becomes adult at the same time
t
- in other words, you may imagine that at the beginning of each second, first the appropriate lily pads die and then the appropriate lily pads become adult.
Input
The first line contains an integer
1 ≤ T ≤ 3
- the number of test cases. The only input file with
T > 1
is the sample shown below.
T
test cases follow, each ends with a blank line.
The first line contains three integers
n
,
w
and
d
- the number of lily pads, the width of the river, and Oňo’s jump distance, where
1 ≤
n
≤ 500 000
and
1 ≤
d
<
w
≤ 10
9
.
n
lines will follow, each containing three integers
m
i
s
i
e
i
describing one lily pad: its distance in meters from the left bank, the time it turns adult, and the time it grows old.
0 <
m
i
<
w
and
1 ≤
s
i
<
e
i
≤ 10
15
.
No two lily pads with the same position
m
i
will be alive at the same time, in particular if any two lily pads have the same
m
i
, one will die at least a second before the other becomes adult.
Output
For each test case, output two integers
e
and
t
in a single line, where
e
is the earliest time at which Oňo can jump all the way from the left to the right bank of the river without stopping, and
t
is the total number of seconds during which he can do so (not necessarily continuously from
e
).
If Oňo can never cross the river, print
e
as
−1
.
Examples
Input:
3
7 60 10
10 1 10
20 1 7
20 8 11
40 1 20
50 4 15
30 5 12
30 1 3
2 100 80
1 1 5
81 5 123
20 5 1
1 1 189
2 1 2
3 1 2
4 1 2
2 109 189
3 109 189
4 109 323
1 281 462
2 281 323
3 281 323
2 337 743
3 337 462
4 337 462
1 616 743
3 616 743
4 616 1016
1 874 1327
2 874 1327
3 874 1327
4 1163 1327
Output:
5 4
-1 0
1 681
In the first case, at time 5, the first, second, fourth, fifth, and sixth lillies are alive, and Oňo can jump across. He can do so until the 7th second for a total of 2 seconds, when the second lily pad dies, then again from the 8th second to the 10th second, after which the first lily pad dies and the river becomes uncrossable forever.
In the second case the lily pads just barely miss themselves, and Oňo can never get across. | 34,507 |
Random modulo n (RANDMOD)
Kubík went to buy a pizza. To his surprise, the pizza box was made out of recycled… punch cards!
With his eagle eye, he deciphered the program the punch cards described:
n = read_input();
ans = 0;
while(n > 0)
{
ans = ans + 1;
n = random() % n;
}
r
a
n
d
o
m
()
is a function which returns uniformly random non-negative integers, and % is the modulus operator.
Now he wonders what the expected value of
a
n
s
would be for a given initial value of
n
, and he is unable to enjoy his pizza until someone computes the answer for him.
Input
The first line contains an integer
1 ≤
T ≤ 5
- the number of test cases.
Each of the next
T
lines contain a single integer
n
, where
1 ≤
n
≤ 300 000
. The sum of
n
within an input file won't exceed 300000.
Output
Output the expected value of the variable
a
n
s
– that is, the sum of
v
×
(probability that
a
n
s
will end up with value
v
), for all possible values
v
.
Your answer will be considered correct if the absolute or relative error does not exceed
10
−9
. Make sure to print enough decimal places.
Example
Input:
2
2
47
Output:
1.5
4.4379638417
In the first case, either
r
a
n
d
o
m
()%2 = 0
with probability
1/2
, which leads to
a
n
s
= 1
, or
r
a
n
d
o
m
()%2 = 1
with probability
1/2
, after which we certainly get
r
a
n
d
o
m
()%1 = 0
, so
a
n
s
= 2
. Expected value of
a
n
s
is therefore
1 × 1/2 + 2 × 1/2 = 1.5
. | 34,508 |
The Cow Gathering (COWGATH)
Cows have assembled from around the world for a massive gathering. There are
N
cows, and
N−1
pairs of cows who are friends with each other. Every cow knows every other cow through some chain of friendships.
They had great fun, but the time has come for them to leave, one by one. They want to leave in some order such that as long as there are still at least two cows left, every remaining cow has a remaining friend. Furthermore, due to issues with luggage storage, there are
M
pairs of cows
(a
i
,b
i
)
such that cow
a
i
must leave before cow
b
i
. Note that the cows
a
i
and
b
i
may or may not be friends.
Help the cows figure out, for each cow, whether she could be the last cow to leave. It may be that there is no way for the cows to leave satisfying the above constraints.
Input
Line
1
contains two space-separated integers
N
and
M
.
Lines
2 ≤ i ≤ N
each contain two integers
x
i
and
y
i
with
1 ≤ x
i
, y
i
≤ N
and
x
i
≠ y
i
indicating that cows
x
i
and
y
i
are friends.
Lines
N+1 ≤ i ≤ N+M
each contain two integers
a
i
and
b
i
with
1 ≤ a
i
, b
i
≤ N
and
a
i
≠ b
i
indicating that cow
a
i
must leave the gathering before cow
b
i
.
It is guaranteed that
1 ≤ N, M ≤ 10
5
.
Output
The output should consist of
N
lines, with one integer
d
i
on each line such that
d
i
= 1
if cow i could be the last to leave, and
d
i
= 0
otherwise.
Example
Input:
5 1
1 2
2 3
3 4
4 5
2 4
Output:
0
0
1
1
1 | 34,509 |
Machine Cooling II (MACHCOOL2)
Duck is a busy guy who has
N
tasks to do in a single day, each task has four sub tasks. The i-th task is scheduled at the
S
i
second starting from 00:00:00, for example, 65 is 00:01:05 and 82800 is 23:00:00, and its j-th sub task requires
D
i,j
seconds to complete. That is, the j-th sub task of i-th task ends at S
i
+ D
i,j
second. Duck plans to buy some machines to help him complete the tasks automatically. One machine can only deal with one task at the same time, but can deal with all four sub tasks simultaneously. Therefore, if any of the sub tasks of that task is not finished, the machine cannot deal with next task. If the whole task is finished, it can deal with the next task immediately without waiting.
However, Duck doesn't want that happens because he wants the machines to be more durable. He wants to maximize the cooling time of each machine whenever it completes a task. Given that the maximum cooling time of each machine is 86400, no matters at what second a machine completes a task, but the cooling time must be the same for all machines. What is the maximum cooling time that every machine can have if Duck uses as few machines as possible to complete all tasks by distributing it optimally?
Input
The first line is the number of test cases
T
. (1 ≤ T ≤ 20)
For each test case, it starts with the number of tasks
N
. (1 ≤ N ≤ 100)
Following N lines, each consisting of five integers: the second counting from 00:00:00 that the i-th task is scheduled at
S
i
, the seconds required to complete the j-th sub task
D
1
,
D
2
,
D
3
,
D
4
. (1 ≤ S
i
≤ 86399, 1 ≤ D
i,
j
≤ 86400 - S
i
)
Output
Output the maximum cooling time that every machine can have.
Example
Input:
2
6
39999 7643 9987 13924 694
2000 3100 3804 2010 1999
4900 15238 28098 27777 27777
28813 11186 15742 886 20016
70000 200 300 400 500
51234 3555 30 7000 24567
3
52024 10000 7321 8864 20
62024 7321 10000 20 8864
72024 20 8864 10000 7321
Output:
2405
0
Explanation
In case 1, Duck needs two machines for task {2, 4, 6} and {1, 3, 5}, the answer is then 2405 choosing the cooling time of 2405 and 7322.
In case 2, one machine is enough but there is no gap between each task. | 34,510 |
Lucifer and Magical Substrings (MAGSUB1)
Lucifer MorningStar is interested in deepest desires of Zing. Being a programmer Zing said he has a desire of knowing number of magical substrings in a string. A substring of string S is said to be magical if it contains at least one magical character (A character is magical if its value is prime, and we assign values to characters as: A is assigned 1, B is assigned 2 ... Z is assigned 26). So you have to calculate total number of magical substrings for S in order to help Lucifer who is absolutely newbie in programming, so that he does not disappoint Zing.
Input
First line contains number of test cases. (1 <= T <= 10).
For each case input will contain two lines:
First line contains length of string N (1 <= N <= 10^5).
Second line will contain a string S of length N. String will only contain uppercase letters.
Output
For each test case output a single integer denoting number of magical substrings of S in new line.
Example
Input:
1
3
ABC
Output:
5 | 34,511 |
Subset with all Digits (THECODE)
Given a list of n d-digit numbers, choose the smallest subset from the list that covers all the digits [0 - 9].
Input
First line contains a positive integer T representing number of test cases.
Next line contains two numbers n and d, where n is the size of the list and d is number of digits in each number.
Next n lines follow each containing a d digit number made from [0 - 9].
1 ≤ t ≤ 100
1 ≤ n ≤ 1000
1 ≤ d ≤ 1000
Output
Output the length of the smallest subset that covers all digits [0 - 9]. Return -1 if not possible.
Example
Input:
2
4 5
01234
56789
01456
13452
4 5
11234
56789
01456
13452
Output:
2
3
Explanation
Smallest set will be {01234, 56789}
Smallest set will be {11234, 56789, 01456} | 34,512 |
Reduce the array (REDARR2)
Given an array of size n, you need to reduce the array. In one step, remove any two elements from the array and add their sum instead. Continue addition and removal until no further reduction possible. Output the minimum cost of reduction possible for the given array.
Input
First line contains a positive integer T representing number of test cases.
Next line contains a number n denoting the size of array.
Next line contains N space separated positive integers (A[i])
1 ≤ T ≤ 50
1 ≤ n ≤ 10
6
1 ≤ A[i] ≤ 10
6
Output
Output minimum cost of reduction.
Example
Input:
2
4
1 6 3 20
3
2 2 2
Output:
44
10
Explanation:
Example 1:
Remove {1,3} and insert 1+3=4, array becomes [4 6 20], cost=1+3=4
Next remove {4,6} and insert 4+6=10, array becomes [10 20], cost=4+6=10 and overall cost=4+10=14
Next remove {10,20} and insert 10+20=30, array becomes [30], cost=10+20=30 and overall cost=14+30=44
Array cannot be reduced further, hence reduction cost is 44. This sequence of reduction also gives the minimum possible cost. You will see all other sequences give greater or equal cost.
Example 2:
Remove {2,2} and insert 2+2=4, array becomes [4 2 ], cost=2+2=4
Next remove {4,2} and insert 4+2=6, array becomes [6], cost=4+2=6 and overall cost=4+6=10
Array cannot be reduced further, hence reduction cost is 10. | 34,513 |
Color Play (RGBRED)
Given a color string consisting of primary colors only (Red, Green, Blue), any two adjacent colors can be combined to form the third color. Print the smallest possible length of the color string after all possible combinations.
Input
First line contains a positive integer T representing number of testcases.
Next line contains a number n denoting the size of color array.
Next line contains a n size color string
1 ≤ T ≤ 100
1 ≤ n ≤ 10
5
Output
Output minimum possible length of the final color string.
Example
Input:
2
3
RGB
4
RGBR
Output:
2
1
Explanation:
Example 1:
[RG]B → BB
Example 2:
[RG]BR → B[BR] → [BG] → R | 34,514 |
Nahid The Reporter (MASUMREPORT)
Nahidul Islam Sayel is a reporter for SIU Daily Journals. One day, while writing an article, he decided to find out the average letter in a given text. There are three steps to find the average letter:
He counts the number of times each letter repeats in the given portion of the newspaper.
He adds up all the repeated values and calculates their average.
He ignores other symbols or digits that are not letters.
The average is always rounded to the nearest whole number. If there is any fraction value 'f', the average will be 'f+1'.
Let's discuss an example: If there is a string "aabbc", where 'a' appears 2 times, 'b' appears 2 times, and 'c' appears 1 time, the total count of letters is (2+2+1) or 5.
The average is 5/3 = 1.67, which is rounded up to 2. This is the average value of letters for this string.
Sometimes, Nahidul gets tired, and it's challenging for him to find the result, so he needs your help. Help him with this task.
Input
The first line contains a line of string (a portion of newspaper) 's' (all lowercase characters) of n characters where 2 ≤ n ≤ 10
6
.
Output
Find out the average value of a string. Print "YES" (without quotes) and print the answer if it exists for any letter.
Otherwise print "The Nearly Answer is :" (without quotes) and the strictly less value than the answer.
Remember that the result will not exceed 32-bit data.
Example
Input:
aabbc
Output:
YES
2
Input:
aaaaa eeeee ccccbbddffg2
Output:
The Nearly Answer is :2
Explanation
Example 1 has described above.
In example 2, a=5, e=5, c=4, b=2, d=2, f=2, g=1 and as stated in the third condition, character '2' is ignored.
Total = 5+5+4+2+2+2+1 = 21 and average = 21/7 = 3. As 3 is not frequency of any letter, So strictly less than 3 is 2, which is the answer. | 34,515 |
Richest_Beggar (RCB)
Akash has recently joined a new company and on his first day at office his colleague Mr. Goyal (who is always ready to mock him :XD) gave him an interesting problem to solve.
Assume
N
beggars, numbered from 1 to
N
are standing outside a temple. It is given that '
k
' people visit the temple on that particular day.
Every person who comes out of the temple selects some beggars from
'l'
to
'r'
and gives each beggar from
'l'
to
'r'
1$ each.
The task is to find out the beggar (or beggars) who gets the maximum amount of money at the end of the day.
Akash does not want to get insulted on the first day, so he has asked you to help him.
Input
The first line of input contains an integer N denoting the number of beggars.
The second line contains an integer 'k' denoting the number of people who visit the temple.
Each of the next k lines contains two integers 'l' and 'r'.
Output
The first line of output contains the maximum amount of money a beggar gets.
The next line consists the beggars who get the maximum amount of money at the end of the day.
Constraints
1 ≤ N ≤ 200000
1 ≤ k ≤ 100000
1 ≤ l, r ≤ 100000
Example
Input:
6
3
1 3
2 4
5 6
Output:
2
2 3 | 34,516 |
Lasertag (LASERTAG)
As is tradition, one afternoon of Výberko is without a contest. On that afternoon, some fun optional activity is usually planned for those extroverted enough to go out and do something. One time, it was laser tag!
The battles were fierce, and the legends stay with us to this very day. At one point, they say, there was a temporary blackout on the battleground and the lights went out.
Each participant, at this point already a seasoned veteran with immaculate aim, prepared for the power to jump back on, reigniting the fierce battle. It was incredibly important to achieve as many points once it did, as surely the blackout caused the score counters to be reset to 0.
As all legendary warriors think alike, they all came up with the same strategy:
1. Point your laser gun north, i.e. in the positive Y-axis direction. (All participants are from Výberko, so it is ordinary for them to think in these terms.)
2. Once the power comes back on, start turning in the direction of your dominant hand at a constant speed of 1 degree per second.
3. Whenever you face someone, shoot them instantly. (If there are multiple people standing in that direction, shoot them all.)
4. After 360 seconds, when everyone is facing north again, stop and assess the results. Brag about your score.
Player A gets 1 point for shooting player B, if at that time player B has not shot player A yet.
All the participants came back to Výberko bragging about how many points they scored.
Paulinka stayed in the computer lab bashing her head against the 10 point problem that everyone else solved in the morning. Their bragging is getting on her nerves.
To take them down a notch, she decided to find out how many points everyone *really* got.
Since Paulinka can't even solve a 10 point problem, she needs your help!
Task
Each player can be modeled as a point in a 2D plane.
The Y axis grows in the direction from south to north and the X axis grows from west to east.
At time 0, each player is pointing their laser gun in the positive Y direction. Then, they start turning, either clockwise (right-handed) or anticlockwise (left-handed), all at the same angular velocity.
For the purposes of the problem, both the players and the laser have zero width, and the laser can shoot through players.
Player A gets 1 point for shooting player B if and only if A shot B first (B didn't shoot A yet).
Calculate the score of each player after they complete one full rotation.
Input
The first line contains an integer
t
(
1 ≤ t ≤ 20
) - the number of games.
t
descriptions of games follow.
For each game the first line contains an integer
n
(
2 ≤ n ≤ 300000
) - the number of players. Sum of
n
in a single file will not exceed
300000
.
n
lines follow, each describing one player in the form
x y h
, where
-10
9
≤
x,y
≤
10
9
are their coordinates, and
h
is the character L if they're left-handed or R if they're right-handed.
Since players are generally introverted, they have instinctively positioned themselves on different
x
and
y
coordinates: all
x
coordinates in the input are distinct, and all
y
coordinates in the input are distinct.
Output
For each game output
n
lines, the
i
-th of which contains a single integer: the score of player number
i
, in the same order as they appeared in the input.
Example
Input:
2
3
0 0 L
-2 1 R
-1 -1 R
3
0 0 R
-2 1 R
-1 -1 R
Output:
1
1
1
0
2
1
In the first game, Player 1 shoots player 2 long before player 2 shoots player 1 back. Similarly, player 2 gets a point for shooting player 3 and player 3 for player 1. So this particular game looks a bit like rock-paper-scissors.
Being right-handed would not turn out well for the first player. Now player 1 loses to both opponents. | 34,517 |
Honest Rectangle (RECTANGLE)
Pat and Avery are secretive people. They're honest, but not too honest. They don't say more than they have to.
When they are together, their friend Kendall says she is thinking of a rectangle with integer dimensions w and h, such that L ≤ w ≤ h ≤ U. She says she will give Pat the perimeter and Avery the area. She then privately gives the perimeter to Pat and the area to Avery.
They then have the following honest conversation.
Avery: I don't know what w and h are.
Pat: I knew that.
Avery: Now I know what they are.
Pat: I now know too.
In additional to being honest, both Pat and Avery are very smart. They use all the information they have available.
What are the possible values for w and h?
Input Format
Input is two lines. The first line is the integer L, and the second line is the integer U.
Constraints Format
1 ≤ L ≤ U ≤ 1000
Output Format
Ouput the possible values for w and h. Use one line for each pair, and separate the numbers in pair by a single space.
Sort by w and then by h.
It may be that there are no possibilties. (In that case, Kendall must've made a mistake.)
Sample
Input:
1
15
Output:
1 4
3 4
Input:
2
865
Output:
4 13 | 34,518 |
Two Sum Query (TWOSUMQUERY)
You will be given an array
A
of size
N
and also given
Q
queries. In each query you will be given a number
K
. You have to print two number
S
1
and
S
2
. Where
S
1
is the sum of all the elements that are
strictly less than K
, and
S
2
is the sum of all the elements that are
strictly greater than K
.
Input
Input starts with an integer
T
(
1
<=
T
<=
20
), denoting the number of test cases. Each test case starts with two integers
N
(
1
<=
N
<=
10
5
) and
Q
(
1
<=
Q
<=
10
5
).
N
denotes the number of elements in the array and
Q
is the number of queries. The next line contain
N
integers
A
0
,
A
1
,
A
2
, ...,
A
N-1
(
0
<=
A
i
<=
10
9
). Then the next line contains
Q
integers
K
(
0
<=
K
<=
10
9
). For each
K
you have to print
S
1
and
S
2
.
Output
For each test case print
"Case X:"
(without quotes) where
X
is the running test case number. Then next
Q
lines consist of
S
1
and
S
2
for every given
K
in the current test case. Where
S
1
is the sum of all the elements that are
strictly less than K
, and
S
2
is the sum of all the elements that are
strictly greater than K
.
Sample
Input
2
10 5
5 1 0 8 1 13 34 21 3 2
1 2 3 4 35
7 2
6 24 120 1 720 2 1
1 23
Output
Case 1:
0 86
2 84
4 81
7 81
88 0
Case 2:
0 872
10 864 | 34,519 |
One Eight_Nine (OEN)
Suppose you have a number of three digits, which is
P
. Add those three digits and store in
X
. Then subtract
X
from the actual number
P
. After Subtraction, now the resulting number is
N
. In this problem, you are given sum of last two digits of N. Your task is to find the first digit of
N.
For example, suppose
P
= 123,
X
= 1+2+3 = 6,
N
= P - X =123 - 6 = 117. Sum of last two digits is 8. So, in this case, first digit is 1
Input
Input starts with an integer T (1<=1000000), denoting the number of test cases. Each case contains sum of last two digits of N (0 ≤ N ≤ 18).
Output
For each test case, output one line containing "Case
x
:
M
", where
x
is the test case number,
M
is the first digit of
N
.
Example
Input:
2
8
13
Output:
Case 1: 1
Case 2: 5 | 34,520 |
Abul and Prime Numbers (APM)
Mr. Abul is a big fan of
prime numbers
. As a fan of prime numbers, he wants to know whether a prime number
P
can be expressed as
difference of two squared numbers
or not.
In other words you have to calculate two natural numbers
X
and
Y
where
P
=
X^2
-
Y^2
For example, prime number
P
= 5 can be expressed as 3^2 - 2^2 = 9 - 4 = 5, here X = 3 and Y = 2.
Input
Input starts with an integer
T
≤ 100, denoting the number of test cases.
Each case contains an integer
N
(2 ≤ N ≤ 10^18) denoting a prime number.
Output
For each case of input, print X and Y separated by a space if it is possible to express as difference of two squared numbers. Otherwise, print -1.
Example
Input:
3
2
3
5
Output:
-1
2 1
3 2 | 34,521 |
Funny Prime Factorization (SITB)
You will given an integer number N. Find the prime factors of this number.
Input
The input consists of several lines.
Each line consists of one integer N (2 ≤ N ≤ 10
7
)
Output
In each line you need to print the factors of N separated by " x ".
Example
Input:
2
8
6
Output:
2 = 2
8 = 2 x 2 x 2
6 = 2 x 3 | 34,522 |
Being a centipede is tough (VZLA2019B)
Ciempierre is a funny
n-pede
, and arthropod with exactly
N
legs. He likes clothing, and today he bought
N
different shoes and
N
different socks. To get dressed, he has to put exactly one sock and one shoe on every leg.
He is a bit eccentric, and he wants to get dressed every morning in a
different way
. He defines a way of getting dressed as the order he puts his clothes on. In one step, he can choose one leg and one sock
or
one shoe. Two ways of getting dressed are different if there is at least one step where he chooses a different leg or, in case of using the same leg, a different sock or shoe.
For example, if Ciempierre has two legs he will buy two different socks and two different shoes. One way of getting dressed is:
Put sock 1 on leg 1
Put sock 2 on leg 2
Put shoe 1 on leg 1
Put shoe 2 on leg 2
Notice that two ways are not necessarily equal if they make Ciempierre look the same. For example, if we swap the first and second steps on the example explained above, it would have been a different way of getting dressed, but his look would had been the same.
Not all the ways of getting dressed are valid, though. Ciempierre can't put a shoe on a leg
before
putting a sock on that leg first.
Given the number of legs Ciempierre has, can you calculate the number of different ways he can get dressed?
Input
The first and only line of the input will have an integer
N
, being the number of legs Ciempierre has, and for instance the number of different socks and different shoes he bought.
Output
Print the number of different ways he can get dressed. As this number can be really big, you must print it modulo 10^9 + 7
Example
Input:
2
Output:
24
Input:
3
Output:
3240
Input:
1
Output:
1
Input:
10
Output:
540458589
Constraints
1 ≤ N ≤ 10^5 | 34,523 |
Challenge Accepted! (VZLA2019C)
Little Rubdary has been training a lot for the Mathematics and Informatics Olympiads. She has been studying divisibility, and has come with a new problem for you!
Is there a positive number that is divisible by the first
N
natural numbers? If so, can you find the smallest one?
Can you find the answer to
Q
values of
N
?
You gladly accept this challenge, but with one condition: as the answers may be extremely large, you will show them modulo some number
M
Input
The first line contains two integer
Q
and
M
, which specify the number of questions to be answered and the modulo respectively. Then, will follow the descriptions of the
Q
questions.
Output
For each question you must print the answer to the challenge modulo
M
in a single line. In case there is no answer to the question, you must output -1
Example
Input:
5 990901
1
6
12
20
60
Output:
1
60
27720
921726
823252
Constraints
1 ≤ Q ≤ 10
3
1 ≤ N ≤ 3*10
5
2 ≤ M ≤ 10
9 | 34,524 |
Drawing Polygrams (VZLA2019D)
Drawing stars on the last page of a notebook is a very entertaining hobby. Did you know these cute "stars" are actually called polygrams?
Given a regular polygon with
p
vertices, we define a
polygram
p/q
, as the resultant polygon obtained after connecting every i-th vertex with the (i+q)-th vertex.
You may know the polygram 5/2 as
pentagram
Another example is the
hexagram
6/2. Given that 6 and 2 are not coprime, this polygram is composed by two 3/1 polygrams
Given a regular polygon with p vertices, its radius R (the distance from its center to any vertex) and a number q, can you calculate the area of the polygram p/q?
It is guaranteed that the resultant polygon will not be degenerated, i.e q ≠ p/2 and q ≠ p
Input
The first and only line of the input contains three integers
p
,
q
and
r
Output
Print in a single line the area of the resultant polygram p/q with radius r. Print the answer with exactly five decimal places
Example
Input:
5 4 2
Output:
9.51057
Input:
10 4 5
Output:
40.61496
Constraints
3 ≤ p ≤ 10
3
1 ≤ q < p
1 ≤ r ≤ 100
q ≠ p/2 and q ≠ p | 34,525 |
Empanadas (VZLA2019E)
The empanadas are a very famous dish in Venezuela. They consist of a fried dough with the shape of a half moon with delicious fillings, such as cheese, ground beef, chicken, black beans, calamari, etc. They are usually served as breakfast, but a real Venezuelan would have them no matter the time of the day.
Samuel and Sebastian are the best
empanaderos
, and both have their own restaurants. Everyday they sell a
combo
, which consists of a number of empanadas, no matter the filling. The size of the combos is not always the same for all the days.
You are visiting the country for
N
days, and as crazy for empanadas as you are, you will have all the empanadas you can afford during your stay. Also, you are very good friends with Samuel and Sebastian, so you will buy empanadas only from their restaurants. However, you can buy at most one combo in one day.
As a good friend, you would like to see each of their business grow, so you will alternate restaurants depending on the last place you bought a combo. For example, if the last combo you bought was from Samuel's, then the next one you buy must be from Sebastian's. Of course, you can skip buying a combo on any day if you want.
Given the number of empanadas each restaurant offers during
N
days, can you calculate the maximum number of empanadas you can have during your stay, without violating your own rules?
Input
The first line of the input consists of one integer
N
, the number of days of your stay.
The second line will have N numbers A
i
separated with exactly one whitespace. The i-th number will indicate the size of the combo that Samuel's restaurant offers on the i-th day.
The third and last line will have N numbers B
i
separated with exactly one whitespace. The i-th number will indicate the size of the combo that Sebastian's restaurant offers on the i-th day..
Output
Print in a single line the maximum number of empanadas you can have during your stay
Example
Input:
3
20 20 10
5 5 7
Output:
35
Constraints
1 ≤ N ≤ 10
3
1 ≤ Ai, Bi ≤ 20 | 34,526 |
Friendship (VZLA2019F)
I live for a world full of chaos, mayhem is my dream. Sadly, friendship bonds keep the world together. This has to end.
Initially, there are
N
people living in the world, and I know the strength of each one and the friendship bonds between them. A group of connected people will sum up their strengths if attacked (the power of friendship...
disgusting
, right?), so I'm interested in the strength of full groups of connected people, specially in the maximum strength of a group.
I have already set a plan of action, the order in which I will destroy friendships! But, turns out, that when one destroys friendships, people may react and increase or decrease their strength. I need your help to find out how successful my plan is.
I'll give you the initial information (strengths and bonds) and a list of
Q
events, each event will be either a destruction event, or a strength change event.
I need to know the maximum strength of a group after each event.
Input
The first line of input consists of two integers
N
and
M
, the number of people and the initial number of bonds respectively.
Next line will contain
N
integers s
1
, s
2
... s
N
separated with exactly one white space, being s
i
the initial strength of the i-th person.
Next
M
lines will contain two integers a
i
and b
i
, representing a friendship bond between those two people.
The next line will contain a single integer
Q
, the number of events.
The following Q lines will be either:
1 k: Indicating the destruction of bond number k (in the input order)
2 p x: Indicates that the person p changed her strength to x
Output
Print Q lines, the maximum strength of a group after each event.
Example
Input:
5 6
3 3 3 3 3
1 2
1 3
2 3
2 5
3 4
4 5
5
2 1 2
1 5
1 4
2 4 8
2 3 7
Output:
14
14
8
11
12
Constraints
1 ≤ N, M, Q ≤ 10
5
1 ≤ s
i
, x
i
≤ 10
5
1 ≤ a
i
, b
i
≤ N
1 ≤ k
i
≤ M
1 ≤ p
i
≤ N
every bond will be deleted at most once.
between two people there is at most one bond. | 34,527 |
Gentleman s Wallet (VZLA2019G)
Mr. Narciso Armstrong is an exceptionally well educated gentleman. Everything he thinks and does adheres to the highest code of conduct. This includes all matters, even his wallet.
He recently discovered a very noble property of some numbers. If you take one of these numbers and sum all of it's digits to the power of the length of the number, then you get the same number back. Astonished by his discovery, he named these numbers after himself: narcissistic numbers.
For example: 54748 is such a number, as we see that 5
5
+ 4
5
+ 7
5
+ 4
5
+ 8
5
= 3125 + 1024 + 16807 + 1024 + 32768 = 54748. Another such number is 371, as we can also see that 3
3
+ 7
3
+ 1
3
= 27 + 343 + 1 = 371.
Being such a gentleman, Mr. Armstrong will never pay an amount of money that does not have this property. Therefore, if he wants to pay something with price P he will instead pay Q, where Q is the smallest number, greater or equal than P that is narcissistic.
Input
This first line of the input contains the number of tests cases T
T lines follow, each with a single non--negative integer P: the price of an item Mr. Armstrong wants to buy.
Output
For each case, print a single line containing the case number (see sample output for format) and the amount that Mr. Armstrong will pay.
Example
Input:
3
5
280
2543
Output:
Case #1: 5
Case #2: 370
Case #3: 8208
Constraints
• 1 ≤ T ≤ 10
5
• All answers will fit a 32 bit signed integer | 34,528 |
Heroes (VZLA2019H)
Heroes... ugh...
My plan to destroy the world was almost finished, but now heroes have gathered in their last attempt to save the earth (which, as everybody knows, is pretty flat). Heroes formed a defensive
N
×
M
grid, each of the N × M heroes stands in one position of the grid. Also, the hero in position
i, j
has h
ij
life points.
Of course, they stand no chance against my wrath. I'll attack them with
Q
spells, the i-th spell will have power p
i
and will attack the submatrix with corners (r1
i
, c1
i
) and (r2
i
, c2
i
). Heroes can decide how to distribute the power of the spell over the heroes in the attacked submatrix, so, for each spell, each hero of the submatrix will decrease his life points by a number of integer points (possibly zero), such that between all the heroes of the submatrix take all the p
i
points of damage. Of course, a hero can only take more damage if his life is greater than zero. Note that the damage they receive will accumulate over all the Q spells.
If heroes cannot receive the damage points of a spell, my spell will reach the (flat) earth and immediately destroy it.
Assuming heroes know the sequence of spells I'll use, can they save the earth if they work optimally?
Input
In the first line, two integers, N and M, the number of rows and columns in the grid.
Next N lines, each one contains M integers h
ij
, the initial life points of each hero.
Then a line with integer Q, the number of spells.
Then follow Q lines, each with 5 integers: r1
i
, c1
i
, r2
i
, c2
i
, p
i
.
Output
Print ”BOOM!” (without quotes) if the earth is destroyed, print ”ugh” (without quotes) otherwise.
Example
Input:
2 3
2 1 3
2 4 4
2
1 1 2 2 7
1 2 2 3 9
Output:
ugh
Input:
2 3
2 1 3
2 4 4
2
1 1 2 2 7
1 2 2 3 10
Output:
BOOM!
Constraints
1 ≤ N ≤ 10
1 ≤ M ≤ 10000
1 ≤ Q ≤ 500
1 ≤ r1
i
≤ r2
i
≤ N
1 ≤ c1
i
≤ c2
i
≤ M
1 ≤ p
i
, h
ij
≤ 10
4 | 34,529 |
Koala Fan (VZLA2019K)
Andy is a really cute person and he wants to buy a koala. There are
n
available koalas, for each koala its beauty and cost are known. There are two accepted types of money in the world: donuts and polygons, so each koala cost can be either in donuts or polygons. Due the bad relations between The Linear States and Exponenzula no money changes between the types are allowed.
Help Andy to find two
different
koalas with the maximum total beauty so that he can buy both at the same time.
Input
The first line contains three integers
n
,
d
and
p
the number of koalas, the number of donuts and polygons Andy has.
The next
n
lines describe koalas. Each of these lines contain two integers b
i
and p
i
the beauty and the cost of the i-th koala, and then a letter "D" or "P", describing in which type of money is the cost of koala i: in donuts or in polygons, respectively.
Output
Print the maximum total beauty of exactly two koalas Andy can buy. If he can't buy two koalas, print "sad:(".
Example
Input:
3 7 6
10 8 D
4 3 D
5 6 P
Output:
9
Input:
3 10 10
5 5 D
5 5 D
10 11 P
Output:
10
Constraints
• 2 ≤ n ≤ 100000
• 0 ≤ d, p ≤ 100000
• 1 ≤ b i , p i ≤ 100000 | 34,530 |
Learn You a Haskell for Great Good! (VZLA2019L)
Gus is really smart guy. He really like challenges and he wants to be the best functional programmer in the world. He knows that the best way to start is reading the
Learn You a Haskell for Great Good!
book. But Gus isn’t so good at making decisions, nevertheless Gus is super good making “problem resolver” friends. So, let's solve this problem and help Gus!
There are
n
chapters in the book, the time that takes to move from the chapter
i
to the chapter (i+1) or vice versa, is t
i
. The time to move from the chapter n-th to the first one, or vice versa, is t
n
(yes, Gus sometimes is weird and starts to read from the end of the book). Also, all the chapters have different difficulty for Gus. The difficulty of the i-th chapter is d
i
.
Gus tries to read some chapters each day in the morning. He does the following steps each morning:
He chooses two different chapters i and j.
He starts to read the first selected chapter.
When he finished the first chapter he moves to the next chapter (in one of the two possible directions).
He reads all chapters between i and j i.e. (i, i + 1 ... j) or (i, i − 1 ... j)
But Marcos is a competitive person and he wants to be the best functional programmer too. So each day in the morning he takes away some consecutive chapters of Gus’s book and he puts them back in the night. Gus can't stand the disorder, so he can't read the chapters in a non-consecutive order (remember that for Gus the consecutive of the chapter i is the chapter i+1 or the chapter i-1).
If the two chapters that Gus chooses are x-th and y-th, we can estimate the energy the morning reading takes to him as 2 * (d
x
+ d
y
) + time(x, y). Since Marcos takes away chapters on exactly one of the two sequences connecting x and y, the time time(x, y) between chapters x and y is uniquely defined.
In the i-th day Marcos will take away the chapters between a
i
and b
i
. More formally, if a
i
≤ b
i
, Marcos takes away the chapters with indices from range [a
i
, b
i
], otherwise he takes away the chapters with indices from [a
i
, n] ∪ [1, b
i
].
Please help Gus to decide which two chapters he should choose in order to consume the most energy.
Input
The first line contains two integer n and m, denoting number of chapters and number of days, respectively.
The second line contains n integers t
1
, t
2
... t
n
, the time between consecutive chapters.
The third line contains n integers d
1
, d
2
... d
n
, the difficulty of chapters.
Each of following m lines contains two integers a
i
and b
i
describing each new day. There are always at least two different chapters Gus can choose that are not affected by Marcos.
Output
For each day print the answer in a separate line.
Example
Input:
3 3
5 1 4
5 1 4
3 3
2 2
1 1
Output:
17
22
11
Constraints
(3 ≤ n ≤ 10
5
, 1 ≤ m ≤ 10
5
)
t
1
, t
2
... t
n
(1 ≤ t
i
≤ 10
9
)
d
1
, d
2
... d
n
(1 ≤ d
i
≤ 10
9
)
a
i
and b
i
(1 ≤ a
i
, b
i
≤ n) | 34,531 |
Hard Fibonacci (FIBHARD)
The problem author is not a very nice person. He wants you to calculate the
N
th
fibonacci number, which is defined as:
Because the author is not very nice, the size of
N
can be huge, really huge. The exact size of
N
is in the
Constraints
section.
Input
The first line contains a single integer
T
, the number of test cases.
The next
T
lines contain a single integer
N
.
Output
For each of the
T
lines, output the
N
th
fibonacci number, modulo
998244353
.
Example
Input:
5
0
1
1234
345639696828452375
419384601238473729475639183948326177846782649592628790267300203877
Output:
0
1
4936310
213237811
389871463
Constraints
0 ≤
N
≤ 10
15000000
1 ≤
T
≤ 100
Notes
The size of the file will not exceed
15MB
.
Fast input may be required.
Fast languages like
C
/
C++
are recommended. | 34,532 |
K-transfer journey (KTRANS)
There are
N
cities numbered from 1 to N, connected by
M
flights. Note that a flight from city 1 to 2 doesn't necessarily mean there is a flight from 2 to 1, and some cities may not be connected by any flights. Also, there is at most one directed flight from one city to another one. The i-th flight connects city
U
i
with city
V
i
, takes
W
i
seconds, plus a constraint: the current accumulated travel time cannot exceed
L
i
when you are in U
i
and plan to go to V
i
from there
for health reason.
Duck wants to travel, but he will be very tired if he takes too many flights! Therefore, he doesn't want to take more than
K
flights. Can you find out the shortest travel time for all pairs of cities by not taking more than K flights and following the accumulated travel time constraint of each flight?
Input
The first line is the number of test cases
T
. (1 ≤ T ≤ 20)
For each test case, it starts with
N
,
M
,
K
. (2 ≤ N ≤ 50, 0 ≤ M ≤ N × (N - 1), 1 ≤ K ≤ N - 1)
Following M lines, each consisting
U
i
,
V
i
,
W
i
,
L
i
. (1 ≤ U
i
, V
i
≤ N where U
i
≠ V
i
, 1 ≤ W
i
≤ 10
4
, 1 ≤ L
i
≤ 10
4
× 50)
Output
Output a N × N distance matrix, printing out the shortest travel time for all pairs of cities. If one city is not reachable from one city, print out -1 instead.
Example
Input:
2
8 15 3
1 2 4 10
1 7 7 28
1 8 4 27
2 3 9 34
2 6 6 14
2 7 8 7
2 8 1 12
3 5 10 24
5 3 8 39
5 4 6 28
5 6 5 11
6 5 6 9
7 2 4 6
7 6 7 12
8 3 3 3
6 9 5
1 2 10 31
1 3 14 58
1 5 23 24
3 1 12 12
3 2 4 19
4 1 20 53
4 5 25 47
5 4 13 47
6 2 4 39
Output:
0 4 13 -1 23 10 7 4
-1 0 4 18 12 6 8 1
-1 -1 0 16 10 15 -1 -1
-1 -1 -1 0 -1 -1 -1 -1
-1 -1 8 6 0 5 -1 -1
-1 -1 14 12 6 0 -1 -1
-1 4 13 19 13 7 0 5
-1 -1 3 19 13 -1 -1 0
0 10 14 36 23 -1
-1 0 -1 -1 -1 -1
12 4 0 48 35 -1
20 30 34 0 25 -1
33 -1 47 13 0 -1
-1 4 -1 -1 -1 0
Explanation
Select some results to explain, won't go through all..
In case 1, 1 → 3 is 13 through 2, rather than 7 through 8 because 1 → 8 is 4, and 8 to 3 has a accumulated time constraint which is 3.
8 → 6 is not reachable although there is exactly one path connecting them and within K, the constraint of 5 → 6 is 11, which is larger than accumulated time of 13.
In case 2, 5 → 2 is not reachable. Only one path connecting 5 to 1 which takes 33. From 1 → 2 the shortest time is 10 but its constraint is 31 which is larger than 33. So we pass through 3 instead and the total time becomes 47. Unluckily the constraint of 3 → 2 also limits the reachability. | 34,533 |
Game of Square (CBIT01)
A and B are playing a game. They are given a number N. They make moves in turn, A playing first. Each move consists of subtracting a perfect square (not less than 1) from the number, the player who faces 0 loses. You are given a number N, you have to find out whether A can win the game, if both A and B play optimally.
Input
The first line contains T - the number of test cases. The next T lines contain a number n.
Output
For each test case, print "Win" if A can win the game, or else print "Lose", separated by new line.
Constraints
1 ≤ T; N ≤ 10
5
Example
Input:
5
1
2
3
1
10
Output:
Win
Lose
Win
Win
Lose | 34,534 |
Minimum string moves (ILD18MSM)
We have two strings A and B which are permutations of the same set of characters. We need to change these strings to obtain two identical strings by performing the following operations:
swap two consecutive characters of a string
swap the first and the last characters of a string
The operation can be performed on either string. Return the minimum number of moves that we need in order to obtain two equal strings?
Constraints
1 < length(A) = length(B) ≤ 2,000
All the input characters are between 'a' and 'z'
The count of each distinct character in A is identical to the count of the same character in B.
Input
First line: String A.
Second line: String B.
Output
Minimum number of moves.
Example
Input:
aab
baa
Output:
1 | 34,535 |
Blind Escape II (BLINDESC)
Illidan Stormage, the blind Warcraft hero is thrown in a maze for punishment. Being a blind hero, he cannot see anything but he can sense which direction is North, East, South and West.
Assume that the maze is laid out on a grid, and each grid location is either blocked or free or contains a demon. He has four possible moves: North, East, South, and West. Illidan starts from a free location at time
t = 0
, and his goal is to kill all the demons within time
T
. Illidan kills a demon immediately (takes
0 unit
of time) whenever he lands on a grid location containing a demon, however making a move to an adjacent cell takes exactly
1 unit
of time. If Illidan attempts to move out of the grid or attempts to move to an obstacle, he will stay in his current location but it will still cost him
1 unit
of time. When Illidan kills the last demon, he is
immediately
freed from the maze but if he fails to kill all the demons within time
T
, he will be trapped in the maze for eternity.
Keep in mind that Illidan is blind, so he may get confused while making a move. To avoid all this chaos, he decides to follow a rather simple strategy. Before he starts his journey to hunt and kill all the demons, he selects four real numbers:
P
N
,
P
E
,
P
S
and
P
W
denoting the probability to move North, East, South and West respectively. No matter where he is, he will always attempt to move North with probability
P
N
, East with probability
P
E
, South with probability
P
S
, and West with probability
P
W
.
Given the description of the maze, the location of all the demons, Illidan's starting position and the probabilities of each move, calculate the probability that Illidan will be able to kill all the demons before the time runs out.
Assume the grid will be of dimensions
N x M
and will contain
K
demons.
Input
The first line of the input contains an integer
Q
, denoting the number of test cases. Then the description of
Q
test cases follow. The first line of every test case will be a blank line.
The second line contains three space separated integers,
N
,
M
and
T
, denoting the number of rows, the number of columns of the grid and the time by which Illidan needs to kill all the demons respectively. The third line contains four space separated real numbers
P
N
,
P
E
,
P
S
and
P
W
in that order. All these numbers will contain at most
2 digits
after the decimal point.
Each of the next
N
lines will contain exactly
M
characters on each line describing the grid. The grid will only consist of the characters
.
@
#
and
*
.
.
indicates a free cell.
@
indicates Illidan's starting position which is also a free cell and will occur exactly once.
#
denotes an obstacle.
*
denotes the location of a demon, there can be at most one demon in a cell.
Constraints
1 ≤ Q ≤ 5
1 ≤ N, M ≤ 8
1 ≤ T ≤ 16777216
1 ≤ K ≤ 3
P
N
+ P
E
+ P
S
+ P
W
= 1
Output
For each test case, print the probability of Illidan escaping the maze in a single line. Error less than
10
-6
will be ignored.
Example
Input:
3
1 2 3
0 0.5 0 0.5
@*
1 8 64
0 0.5 0 0.5
@......*
8 8 10000000
0.05 0.25 0.45 0.25
##....#.
.##.....
.*#.##..
.##..*#.
...###..
.#.#....
.#.#.#..
@#.*.#..
Output:
0.875000000000
0.693211582717
0.157323987423
Credits
Problem name and story inspired by
LightOJ 1426 - Blind Escape
.
Or if you prefer a not so blind version
SPOJ NBLINDESC- Not So Blind Escape
. | 34,536 |
Solution to all the problems (KTH_INDEX)
People have been coming to the wise man, complaining about the same problems every time.
One day he told them a joke and everyone roared in laughter.
After a couple of minutes, he told them the same joke and only a few of them smiled.
When he told the same joke for the third time no one laughed.
The wise man smiled and said:
"You can't laugh at the same joke over and over. So why are you always crying about the same problem?"
He has also created a very simple game to cheer the people up. The game is as follows:
You are given a sequence A of N integers.
The task is to answer Q queries on the given sequence. For each query, you will be given four space-separated integers L, R, P, K.
Print the index of K
th
occurrence of P in L to R(inclusive). If no such index exists, print -1.
Input
The first line contains two space-separated integers N and Q.
The second line contains N space-separated integers. (1-based indexing)
Following Q lines contain,
Four integers L, R, P, K.
Output
For each query, print a single line containing one integer between 1 to N i.e. index of the K
th
occurrence of P in L to R.
Print -1 if no such index exists.
Constraints
2 ≤ N, Q ≤ 10
5
1 ≤ A
i
≤ 10
6
1 ≤ L < R ≤ N
1 ≤ P ≤ 10
6
1 ≤ K ≤ N
Example
Input:
10 3
1 1 2 1 2 3 1 2 3 4
1 10 2 3
1 5 2 3
5 9 3 2
Output:
8
-1
9 | 34,537 |
Not So Blind Escape (NBLINDESC)
Illidan Stormage, the blind Warcraft hero is thrown in a maze for punishment. Being a blind hero, he cannot see anything but he can sense which direction is North, East, South and West.
Assume that the maze is laid out on a
N x M
grid, and each grid location is either blocked or free. Illidan starts from a free location at time 0, and his goal is to escape from the maze. He has four possible moves - move to North, East, South or West. Making a move to an adjacent cell takes
exactly 1 unit
of time. If Illidan attempts to move out of the grid or attempts to move into an obstacle, he will stay in his current location but it will still cost him 1 unit of time. There is exactly one exit in the maze, located in one of the free cells. Illidan escapes
immediately
whenever he reaches the exit.
Keep in mind that Illidan is blind, so he may get confused while making a move. To avoid all this chaos, he decided to follow a rather simple strategy. Before he starts his journey to escape the maze, he selects four real numbers:
P
N
,
P
E
,
P
S
and
P
W
denoting the probability to move North, East, South and West respectively. No matter where he is, he will always attempt to move North with probability
P
N
, East with probability
P
E
, South with probability
P
S
, and West with probability
P
W
. At any moment, Illidan must attempt to make a move in one of these four directions. In other words, this means that
P
N
+ P
E
+ P
S
+ P
W
= 1
.
Illidan does not want to be stuck in the maze for too long. He has information about the maze so he knows his starting position, the location of the exit cell and all the free cells and obstacles initially. Before he attempts to escape, he would like to set the values
P
N
,
P
E
,
P
S
and
P
W
such that the
expected time for him to escape the maze is minimized
.
Given the description of the maze, Illidan’s starting position and the location of the exit cell, calculate the minimum expected time for Illidan to escape. You can safely assume that Ilidan’s starting cell and the exit cell will
always be connected
, that is, it will be possible to reach the exit cell via some sequence of moves.
Input
The first line of the input contains an integer
T
, denoting the number of test cases. Then the description of
T
test cases follow. The first line of every test case will start with a blank line.
The second line contains two space separated integers,
N
and
M
denoting the number of rows and the number of columns of the grid. Each of the next
N
lines will contain exactly
M
characters on each line describing the grid. The grid will only consist of the characters
.
@
#
and
*
.
.
indicates a free cell.
@
indicates Illidan’s starting position which is also a free cell and will occur exactly once.
#
denotes an obstacle.
*
denotes the location of the exit cell, is of course a free cell and will occur exactly once.
Constraints
1 ≤ T ≤ 32
1 ≤ N, M ≤ 8
Output
For each test case, print the expected time for Illidan to escape the maze if he chooses the probabilities optimally in a single line.
Absolute
error less than
10
-6
will be ignored.
Sample Input
2
1 2
@*
3 3
@..
#.#
..*
Sample Output
1.0000000000000
16.360252929211
Credits
Problem name and story inspired by
LightOJ 1426 - Blind Escape
Or if you prefer a blinder (easier) version
SPOJ BLINDESC - Blind Escape II | 34,538 |
Bipartite Permutation (BPM)
Given a positive integer
N
, consider any permutation of all the numbers from
1
to
N
. It is required to create two partitions,
P
1
and
P
2
, from these numbers such that
|sum(P
1
) – sum(P
2
)|
is minimum, where
sum(X)
denotes the summation of all the numbers in partition
X
. A partition is defined to be a non-empty subset of the permutation. In other words, find the minimum absolute difference between the summation of all the numbers in each partition. Note that you cannot leave out any number, every number from
1
to
N
must be part of exactly one partition.
Input
The first line contains an integer
T
, denoting the number of test cases. Each of the next subsequent
T
lines contain a positive integer
N
.
Constraints
1 ≤ T ≤ 1000
2 ≤ N ≤ 10
9
Output
For each test case, first print the case number followed by the minimum absolute difference.
Sample Input
5
2
3
4
5
6
Sample Output
Case 1: 1
Case 2: 0
Case 3: 0
Case 4: 1
Case 5: 1
Challenge
Try the harder version here:
Bipartite Permutation (Hard) | 34,539 |
Bipartite Permutation (Hard) (BPM2)
Given a positive integer
N
, consider any permutation of all the numbers from
1
to
N
. It is required to create two partitions,
P
1
and
P
2
, from these numbers such that
|sum(P
1
) – sum(P
2
)|
is minimum, where
sum(X)
denotes the summation of all the numbers in partition
X
. A partition is defined to be a non-empty subset of the permutation. In other words, find the minimum absolute difference between the summation of all the numbers in each partition. Note that you cannot leave out any number, every number from
1
to
N
must be part of exactly one partition.
To add a little bit more of spice, also find the lexicographically smallest partition
P
1
such that
|sum(P
1
) – sum(P
2
)|
is minimum. To make your life easier, you don’t need to output the entire sequence, only the hash of the sequence as computed by the function below would suffice.
def sequence_hash(sequence, B, M):
result = 0
for number in sequence:
result = (result * B + number) % M
return result
Input
The first line contains an integer
T
, denoting the number of test cases. Each of the next subsequent
T
lines contain three positive integers,
N
,
B
and
M
.
Constraints
1 ≤ T ≤ 1000
2 ≤ N ≤ 10
9
N < B ≤ 10
9
1 ≤ M ≤ 10
9
Output
For each test case, first print the case number followed by the minimum absolute difference and the hash of the lexicographically smallest partition
P
1
.
Example
Input:
12
2 10 1000000000
3 10 1000000000
4 10 1000000000
5 10 1000000000
6 10 1000000000
7 10 1000000000
8 10 1000000000
9 10 1000000000
1000 1000000000 1000000
1000000 1003001 998244353
123456789 987654321 666666667
444444444 666666666 888888888
Output:
Case 1: 1 1
Case 2: 0 12
Case 3: 0 14
Case 4: 1 124
Case 5: 1 1234
Case 6: 0 1247
Case 7: 0 12348
Case 8: 1 123457
Case 9: 0 1000
Case 10: 0 553178755
Case 11: 1 214459309
Case 12: 0 557434257
Challenge
Don't like challenges? Try the easier version here:
Bipartite Permutation | 34,540 |
PIZZA (MOHIBPIZ)
In this problem you are given a pizza. You have to find the maximum number of slices after cutting the pizza
exactly N
times.
Note that it is not necessary to make each slice equal.
For example if
N = 1
then we can make maximum 2 slices. Figure 1 show this.
If
N = 2
then we can make maximum 4 slices. Figure 2 show this.
Input
Input starts with an integer
T (1<=10^6)
, denoting the number of test cases.
Each case contains an integer
N (1 ≤ N ≤ 10^9)
denoting the number of times you can cut the pizza.
Output
For each case of input, output only one integer the
maximum number of slices
.
Example
Input:
2
1
2
Output:
2
4 | 34,541 |
Projectile Motion (PROJECTILE)
Consider a two-dimensional plane. There are
N
poles standing parallel to y-axis. The ith pole has height
Hi
and is between y = 0 and y = Hi and at position
Xi
. The gravity acts along negative y-axis and its value is
10
.
Q
projectiles are launched from origin with the jth projectile launched at an angle
Aj
and with speed
Sj
. For each projectile, print the index of pole that the projectile hits.
The poles in input are arranged in increasing order of
Xi
. If a projectile doesn't hit any pole, print -1. Indices of pole starts from 1. The angle is given in degrees and all other units follow SI.
Constraints
1 <=
N
<= 10^5
1 <=
Q
<= 10^5
1 <=
Xi
<= 10^9
1 <=
Sj
<= 10^9
1 <=
Aj
<= 89
1 <=
Hi
<= 100
Input
All values in input are integers.
The first line contains N.
The next N lines containes two space separated integers Xi and Hi. The Xi's are in increasing order and unique.
The next line contains Q.
The next Q line contains two space separated integers Aj and Sj.
Output
Print Q lines each containing the pole index hit by the jth projectile. If a projectile doesn't hit any pole, then print -1.
Example
Input:
4
1 1
2 3
3 7
6 3
8
10 34
45 20
50 12
60 14
70 65
60 34000000
85 12
81 14
Output:
1
1
2
3
-1
3
-1
4 | 34,542 |
To the Bird-planet (TTBRM)
"Weddings are basically funerals with cake Morty"
Birdperson has invited Rick and Morty to attend his marriage party. Rick doesn't like to go to marriage parties but Morty wants to go, as Birdperson is a very close friend. Also, Birdperson is king of Bird-planet and wants to compensate for the travel expenses for Rick's family. Bird-planet is many light years away from the earth but that is not the problem as Rick has Space Cruiser with hyperspeed.
Space cruiser needs 1 unit of fuel to travel 1 light year but it has a limited capacity 'C' so they may need to refuel in-between. There are many planets between Birdplanet and Earth and the fuel pricing is different on each planet.
Let Earth is numbered as '1' and bird-planet as 'N+1' then they can fuel at n planets (including earth). Distance between any two consecutive planets is 'D' light-years.
Evil Rick wants to maximize the expense of fueling and Birdperson knows this so he put a condition that on arrival there should be zero fuel in the tank.
Your task is to maximize the expense and it is obvious that they can't fuel at bird-planet. Initially, there is zero fuel in the tank.
Input
The first line contains T, the number of test cases. Then the test cases follow.
The first line of each test case contains N, C and D, Number of planets for fueling (including Earth), Capacity of the fuel tank and distance between two consecutive planets
Second-line contains A1 A2 A3… AN, where Ai denotes the price of 1 unit of fuel on ith planet.
Output
For each test case print the maximum possible expense.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 10
5
1 ≤ D ≤ 10
5
D ≤ C ≤ 10
5
1 ≤ Ai ≤ 10
9
Example
Input:
1
3 5 3
1 5 2
Output:
30
Explanation
As N=3 so Birdplanet will be 4th planet and hence they will need to travel 3*3=9 light year.
First they will buy 3 unit fuel from 1st planet to go to 2nd planet, expense: 3*1=3
They will buy 5 unit of fuel (up to full capacity) at 2nd planet, expense: 5*5=25
There will be 2 unit of fuel remaining on reaching 3rd planet so the need to buy only 1 more unit of fuel to reach Birdplanet, expense: 1*2=2
Total expense 3+25+2=30 | 34,543 |
Trailing digits (TRAILDIG)
The story to this problem has trailed off.
Given integers
n
,
m
, and
k
, compute the real number
n
−
m
(also known as
1/
n
m
) and write it as a decimal number in base 10. You can assume that it won’t be a repeating decimal – it can be written with finitely many digits followed by infinite zeros. Print the trailing
k
digits.
Input
The input contains multiple testcases. Their number
1 ≤ T ≤ 15
is in the first line.
Each test case is a single line containing three integers:
n
,
m
and
k
. (
1 ≤
n
≤ 10
9
, 1 ≤
m
≤ 10
5
, 1 ≤
k
≤ 9
)
It is guaranteed that
n
−
m
is not a repeating decimal.
Output
Print the last
k
digits of
n
−
m
after which there are only infinite zeros.
If there are less than
k
digits after the decimal point, do not print the decimal point. You must always print all
k
digits, even if your output has leading zeros.
Examples
Input:
2
2 3 2
2 3 5
Output:
25
00125
2
−3
= 0.125
, so the last two digits are 25.
2
−3
= 0000.1250000
. Ignoring the infinite zeros at the end and the decimal point, the last 5 digits are 00125. | 34,544 |
Fashionable self-describing numbers (SELFNUM)
Task
You decided to start an online dating site for mathematical objects. Every set, number, algebraic structure and lemma can register on your site and start describing its good qualities in its profile.
This is especially easy for numbers which directly describe themselves when you read them. For example, the number
10123133
contains
one
“
0
”,
one
“
2
”,
three
“
1
”s and
three
“
3
”s. We call numbers like that
self describing numbers
, and they are very popular.
A bit more formally, an integer is a self-describing number if we can split it into pairs of ((count, digit), (count, digit), (count, digit), …) where for every (count, digit) pair, our number really contains that digit that many times. All counts must be written without leading zeros and all digits appearing in the number must be specified exactly once.
However, the digit
f
has fallen out of fashion. Any number that contains the digit
f
has no chance.
Consider all self-describing numbers that don’t contain the forbidden digit
f
. Print the
n
-th smallest such number. (The first
n
− 1
self describing numbers are out of your league.)
Input
The input contains multiple testcases. Their number
1
≤ T
≤ 5
is on the first line.
Each testcase is a single line with two integers
n
and
f
, where
1 ≤
n
≤ 10
9
and
0 ≤
f
≤ 9
.
Output
Print the
n
-th smallest self describing number that doesn’t contain the digit
f
.
The input will be chosen so that the answer always exists.
Examples
Input:
2
1 1
1 2
Output:
22
10143133
The number 22 is self describing – we can split it as ((2,2)). It is the smallest self describing number that doesn’t contain the digit 1.
We can read 10143133 as
((1, 0),(1, 4),(3, 1),(3, 3))
. This is the smallest self describing number that doesn’t contain the digit 2. | 34,545 |
Linear Diophantine Equation (COUNTDIO)
Given a positive integer
M
and
N
positive integers
a
1
, a
2
, ..., a
N
. Count the number of non-negative integer tuples
(x
1
, x
2
, ..., x
N
)
such that:
a
1
* x
1
+ a
2
* x
2
+ ... + a
N
* x
N
= M
Input
- The first line contains two integers
N
and
M
.
- The second line contains
N
integers
a
1
, a
2
, ..., a
N
respectively.
Output
- Output only one integer, the number of asked tuples modulo
998244353
.
Constrains
1 ≤
N
≤ 60 000
1 ≤
M
≤ 10
18
1 ≤
a
i
≤ 60 000
1 ≤
a
1
+ a
2
+ ... + a
N
≤ 60 000
Example
Input:
3 10
3 2 5
Output:
4
Input:
5 100000
1 3 4 6 1000
Output:
865762992
Note
My solution runs in less than 0.8s for each input file, 6.3s in total. | 34,546 |
GOOD COMMUNICATION (GCOM)
Binary Representation of a number represents a point (vertex) in the N-th dimensional hyper-cube (N is the number of bits used to represent the number in binary form). Eg. point 3 (011) and 5 (101) are shown in 3-dimensional cube in the figure. As the value of points increases, number of axes to represent it in the hyper-cube increases.
Given an N-th dimensional hyper-cube and an array (of size n) of selected points from the cube. We select its complementary point from the cube. We call communication between these points "GOOD" if the distance between given point and its complementary point is maximum. Distance between two points is defined as the bitwise XOR of two points. Let this complementary point be M. The cost of building communication between them is given by
Cost = 2
n
; where n is position of unset bit which is at farthest distance from MSB in M
To decrease the cost we have two operations:
Type1: ' q l r ' :- we select two positions l and r from the array. Output the point from the array, between the smaller and larger position being selected, which has minimum cost of building the communication. In case there are multiple answers, print the point with minimum value.
Type2: ' u x y ' :- update the point at index x with value y.
NOTE:- ' l r x ' are according to 1-based indexing (1 <= l, r, x <= n)
Constraints
1 <= T <= 20
1 <= n, q <= 10
5
1 <= array elements <= 10
9
Input
First line contains number of test cases. Next line contains n and q representing size of array and number of operations. Next line contains array elements. Next q lines operations of type1 and type2 in the specified format.
Output
Give answer of the required type in new lines.
Example
Input:
1
3 3
2 3 4
q 1 3
u 2 5
q 1 2
Output:
3
5 | 34,547 |
Epidemic Control (IBONEC)
The International bureau of epidemic control has recently found a weird virus which is spreading very rapidly. The infection of this virus happens in a very peculiar way. To any healthy person, it needs 4 infected people to get infected to. While infecting each virus splits into two; First half remains to the infecting guy and other one goes to the healthy guy. This way the newly infected guy gets total viruses equal to all those 4 infected people.
However, due to immunity of body some viruses die immediately. It has been found that the number of viruses dying due to immunity is always equal to the second least number of viruses received from the four infecting people. That means, if four infecting people have v1, v2, v3 and v4 viruses and v1 <= v2 <= v3 <= v4, then the healthy guy will ultimately have v1 + v3 + v4 viruses remaining in the body. After that, this number remains constant in the body. Strangely, this epidemic does not spread as other epidemics. The infected person with least viruses (here v1) will no longer infect any other person. Also, once infected person cannot be infected again.
The bureau has identified that this virus is very lethal as it's population is increasing very rapidly. They have discovered a vaccine which costs 1$ to kill 1 virus. Since, it is an international bureau , they can afford this cost for the cause of humanity. But they need to know first, how much would it cost in total to get rid of this virus forever, given that N people have already been infected by this virus.
You have been asked by this bureau to compute the total number of viruses spread among the world. Oh yes, this infection was started by four culprits who went on a tour in a jungle and ate up some hyenas there. When these four came back from the tour, they had 1, 2, 3 and 5 viruses in their bodies respectively.
Input
First line contains a positive integer T (T ≤ 1000). Then T lines follows, each line containing one positive integer N (4 ≤ N ≤ 10
10
).
Output
For each test case print total number of viruses spread in the world, given that total N people has been infected. Since, this can be very huge number, print modulo 1000000007.
Example
Input:
3
5
6
100
Output:
20
36
639154830
Explanation:
For first test N = 5. Given that V1 = 1, V2 = 2, V3 = 3, V4 = 5 and V5 = V4 + V3 + V1 = 9 because V2 viruses died immediately after infection. Thus, total viruses in the world are:
(1 + 2 + 3 + 5 + 9) = 20. | 34,548 |
Yet Another Perfect Square Equation (PERFSQNUM)
Perfect squares are fairly simple concept. A number like 49 is perfect square because it can be written as product of two same natural number i.e. 7 * 7.
On the other hand infinite sequence of numbers can be considered an intriguing concept, because it is not possible to represent all numbers belonging in an infinite sequence easily.
Can read more about infinite sequences
here
.
So one way to represent infinite sequence of numbers is to use an algebraic expression instead of writing all numbers in the sequence.
For example, expression x
2
+ 1 represents the series 2, 5, 10, 17 .... . (Substituting value of x = 1, 2, 3, ... to get the values in the sequence)
Similarly x
2
+ 4 represents the infinite series 5, 8, 13, 20, .... (Substituting value of x = 1, 2, 3, ... to get the values in the sequence)
Given an infinite sequence of numbers of form x
2
+ n, figuring out perfect square numbers within this sequence can be challenging even if checking a number is perfect square is easy.
For example, consider the infinite sequence represented by x
2
+ 771401, only when x = 385700 then x
2
+ 771401 = 148765261401 = 385701
2
is a perfect square. There are no other values of x for which x
2
+ 771401 will be a square.
This is because 771401 is difference between two consecutive squares 385700
2
and 385701
2
. So the infinite sequence represented by x
2
+ 771401 has only 1 perfect square number when x = 385701.
Let us consider one more example x
2
+ 45, only when x = 2, 6 or 22 then x
2
+ 45 is a perfect square. So the infinite sequence represented by x
2
+ 45 has only 3 perfect square numbers when x = 2, 6 or 22.
But infinite sequence represented by x
2
+ 46 contains no perfect square numbers, this is because if it contains such a number then the infinite sequence represented x
2
+ 45 will not have any perfect square numbers which is a contradiction because we know 3 perfect square numbers contained in infinite sequence represented by x
2
+ 45.
In other words given equation x
2
+ n where n is a whole number (i.e. n can take values like 0, 1, 2, 3, 4 ...) find all x in ascending order such that x
2
+ n is a perfect square.
Input
The first line of input file contains a positive integer 't' and next 't' lines contains a string which looks like 'x^2 + n' (example 'x^2 + 3', 'x^2 + 5' etc.).
0 ≤ n ≤ 10
6
Sum of all 'n' in a test file will not exceed 10
6
Output
The output line has to printed for each test case line.
If there are finite number of values of 'x' for which x
2
+ n is a perfect square then print all such x in ascending order separated by comma and space (, ) and enclosed within square brackets. So for 'x^2 + 45' the output line will look like [2, 6, 22].
In case there are no such values of 'x' for which x
2
+ n is a perfect square then print "No Solution" (without quotes and case sensitive). So for 'x^2 + 46' the output line will be "No Solution".
In case there are infinitely many solutions for which x
2
+ n is a perfect square then print "Infinitely Many Solutions" (without quotes and case sensitive). So for 'x^2 + 0' the output line will be "Infinitely Many Solutions"
Example
Input:
3
x^2 + 45
x^2 + 0
x^2 + 46
Output:
[2, 6, 22]
Infinitely Many Solutions
No Solution | 34,549 |
Absurdistans Teaparties (TEAPARTY)
The people in Absurdistan like tea. In fact, it's their favourite drink. But normally, they don't drink their tea alone. They make big tea parties and I've heard the people there drink so much tea they're drunk after the parties. The sad side of the story is, that the people there don't do anything else than go to tea parties. They sit home alone waiting until someone sends them an invitation for a tea party on the national network Teanet™. This network has employed you as a developer.
Strangely, the n citizens of Absurdistan have their n houses built on a line with the same distance between each two adjacent houses. To go with the car from one house to the next, one needs exactly c minutes. And in each house, exactly one citizen lives there.
Teanet™ wants to create an app for the people to help them plan their tea parties. Suppose a citizen living in building x wants to make a tea party in t seconds. For this tea party, he wants to invite all the people living in houses between house l and r (l and r included). He wants to know how much time he has left until he has to send the invitations. We know for every citizen the time he needs to make himself ready. After a citizen receives an invitation, he immediately makes himself ready and then takes the car and goes to the citizen living in building x. We want to know the latest point in time such that x still is able to send the invitations and everyone is here when the party starts. But sometimes, people move out of a building and new people move in, so the time for a citizen in a building to prepare can change.
And since the people return drunk from their parties, it may happen that there are accidents on the streets. If an accident happens, the street from building a up to building b is closed, but only in one direction. The people who don't live in a building between a and b don't care since they can use another street, but the people between a and b need some time more if they want to drive in the same direction as the accident. Because the people in Absurdistan don't really work, the effects of the accident are permanent...
So there are three types of queries:
"invite", followed by four numbers x l r t. x wants to invite all the people between l and r to his tea party. If he wants to start his team party in t seconds, in how many seconds is the latest point in time when he has to send his invitations? All the citizens in Absurdistan always take the direct way (they don't change direction and go back etc.). Note that the result may be negative if the person who wants to send an invitation is already too late. Important: Since the person who invites already knows that he will be inviting, he doesn't need to prepare himself.
"change" followed by two numbers x v. The citizen in building x moved out and the new resident needs v seconds to prepare.
"accident" followed by 3 numbers and a char: l r v d. There was an accident between l and r. All citizens between l and r need v more time if they travel in direction d. Note that this doesn't affect the people from outside if they want to go to a tea party at a location between l and r.
Also note that all indices are 0-based and inclusive.
Input
First line: Three integers n q c. n is is the number of citizens / buildings, q the number of queries and c the time you need between two houses.
On the next line, n values follow: the i-th value is the time the i-th citizen (citizen 0 lives in building 0 etc.) needs to prepare.
Then q lines follow, each with a query as in the description.
Output
For each query of type "invite", output the number of seconds citizen x has left to send the invitation.
Constraints
1 ≤ n, q ≤ 1e5
0 ≤ c ≤ 1e4
The preparation-time for any citizen will never exceed 1e4 and v in query "accident" is also not bigger than 1e4.
Whenever we have a range l r, then 0 ≤ l ≤ r < n holds.
Example
Input:
10 11 2
0 0 0 0 0 0 0 0 0 0
invite 3 6 8 12
accident 6 8 2 l
invite 3 6 8 12
invite 9 6 8 12
change 5 4
invite 3 5 8 16
change 7 6
invite 0 5 8 32
accident 0 9 10 r
change 8 11
invite 5 0 9 50
Output:
2
0
6
4
10
30
Input:
10 10 34
10 23 1 43 12 22 84 17 41 24
invite 2 4 8 333
change 2 11
invite 8 4 9 542
accident 0 9 10 l
accident 0 5 11 r
accident 6 7 22 l
invite 4 2 6 233
invite 8 2 6 542
change 3 1
invite 4 3 3 47
Output:
88
390
49
316
1
Description of First Example
Citizen wants to invite all the people between 6 and 8. Citizen 8 needs 10 seconds to get to citizen 3, so if citizen 3 sends the invitation in any later than 2 seconds, citizen 8 would be too late.
Before the second invitation, there was an accident and Citizen 8 now needs 2 seconds longer because of this.
In the 3rd invitation, the citizens travel to the right and the accident only affects people going to the left. Person 6 needs 6 seconds so if he gets the invitation any later than in 6 seconds, he's too late.
Then, citizen 5 moves out and a new person moves in. This person needs a bit more time to get ready, and when person 3 makes anther party, he needs to send his invitation even earlier.
Then citizen 0 makes an invitation etc., but then another accident happens, now influencing everyone going to the right. A new person moves in building 8 and citizen 5 makes another party. Person 9 needs 8 seconds to get to citizen 5. Person 8 needs 11 seconds to get ready, 2 second to avoid the (first) accident and 6 seconds to get there giving a total of 19 seconds. But person 0 needs even longer: Person 0 doesn't need to prepare, but since he wants to go to the right, he needs to avoid the (second) accident, giving him 10 extra seconds. But he then needs to go to person 5 and it takes him 10 seconds to get there, giving a total of 20 seconds until he arrives. So person 5 needs to send his invitation in 30 seconds.
Edit: Feb 12th, 2020:
Updated the task description to clarify that the person who invites doesn't need to prepare
Edit: Mar 3th, 2020:
Added Constraints | 34,550 |
Supraiden (SUPRAID)
Duck is playing a game named "Supraiden", which is another version of a famous shooting game named "Raiden". On a
D
× 10
9
map, initially Duck is at the left top coordinates (1, 1), and there are
N
enemies at the bottom of the map but with different horizontial position
L
i
. That is, the first enemy is at (D, L
1
), the second one is at (D, L
2
), and so on. The i-th enemy has
M
i
bullets, and he will shoot the j-th bullet at time
S
ij
.
All enemies are fixed, so they cannot move; and Duck can choose to stay at the same position, or move one unit on map horizontally per unit of time. For example, moving from (1, 1) to (1, 5) takes 4 units of time. But Duck can only move to a cell where currently no bullets at there.
Assume Duck will move to right at next unit of time, the following are two examples will cause valid move, followed by two invalid move examples:
(D = Duck, E = enemy, ^ = bullet from enemy)
Valid Invalid (Duck will get hit)
..D.. ..D^. ..D.. ..D^.
..... .^^.. ...^. ...^.
...^. ..... ..^.. ...^.
.EEE. .EEE. .EEE. .EEE.
Bullet speed is one unit on map per unit of time. Shooting takes 0 unit of time, but Duck and enemies can only shoot one bullet per unit of time and shoot vertically. For example, moving from (1, 1) to (1, 5) and shoot immediately only takes 4 units of time. When two bullets collide with each other, both disappear. Collision only occurs when one side shoots before the bullet from another side reaches his current position.
Assume Duck will shoot at next unit of time, the following are two examples will cause valid collision, followed by two invalid collision examples:
(D = Duck, E = enemy, v = bullet from Duck, ^ = bullet from enemy)
Valid Invalid (Duck will get hit)
..D.. ..D.. ..D.. ..D..
..v.. ..... ..^.. ..^..
..^.. ..^.. ..... ..^..
..E.. ..E.. ..E.. ..E..
Duck has infinite amount of bullets, starting at time 0, your task is find the minimum time to kill all enemies without getting hit.
Input
The first line is the number of test cases
T
. (1 ≤ T ≤ 20)
For each test case, it starts with two integers
D
,
N
. (3 ≤ D ≤ 10
9
, 1 ≤ N ≤ 8)
Following N lines, each starts with
L
i
,
M
i
, followed by M
i
distinct integers
S
ij
. (1 ≤ L
i
≤ 10
9
, 1 ≤ M
i
, ≤ 1000, 1 ≤ S
ij
≤ 10
9
)
*L
i
and S
ij
are already sorted in ascending order.
Output
Output the minimum time to kill all enemies.
Example
Input:
3
100 1
1 1 100
5 3
12 9 0 1 4 5 6 7 8 9 19
14 2 12 88
20 5 23 27 29 35 100
6 2
6 7 1 2 3 4 5 6 7
8 1 0
Output:
99
29
18
Explanation
In case 1, Duck can shoot one bullet at time 0.
In case 2, Duck reaches (1, 12) at time 14, and shoots. Then he moves and reaches (1, 14) at time 17 and shoots. Lastly he reaches (1, 20) at 23 and shoots three bullets. The first two bullets collided with the first two bullets shooted by enemy 3, and the last bullet hits the enemy at time 29.
In case 3, Duck reaches (1, 6) but doesn't shoot, then moves to (1, 8) immediately and shoots one bullet. After that, he goes back and reaches (1, 6) at time 13 and shoots. The bullet hits enemy 1 at time 18. | 34,551 |
K-Divisors (KDIV)
The
positive divisor function
is defined as a function that counts the number of positive divisors of an integer
N
, including
1
and
N
.
If we define the positive divisor function as
D(N)
, then, for example:
D(1) = 1
D(2) = 2
D(10) = 4
D(24) = 8
Calculating
D(N)
is a classical problem and there are many efficient algorithms for that. But what if you are asked to find something different? Given a range and an integer
K
, can you find out for how many
N
in the given range,
D(N)
equals
K
?
Input
In the very first line, you’ll have an integer called
T
. This is the number of test cases that shall follow. Every test case contains three integers,
L
,
R
, and
K
.
L
and
R
represent the range and are inclusive.
Constraints
1 ≤ T < 31
1 ≤ L ≤ R < 2
31
1 ≤ K < 2
31
Output
For every test case, you must print the case number, followed by the count of numbers with exactly
K
divisors in the range.
Example
Input:
3
10 10 4
2 13 2
100 10000 100
Output:
Case 1: 1
Case 2: 6
Case 3: 0 | 34,552 |
Random Magic Trick (RANAGIC)
A standard deck of cards has
52
cards in total,
4
suits - Hearts, Diamonds, Clubs, and Spades and each suit has
13
cards (
2, 3, 4, 5, 6, 7, 8, 9, 10, Jacks, Queens, Kings and Aces
). Oompa Loompa is an amateur magician who loves card magics. As you know, many magic tricks are rather simple once you know the secret behind them. Oompa Loompa's favorite trick is the random magic trick. The trick goes on like this. At first, he takes a deck of cards consisting of some suits, and each suit containing some cards, and randomly shuffles them. The magician's trick here is to show there are at least
2
consecutive Kings as well as
2
consecutive Queens in the shuffled deck. As you can see, this trick relies on pure luck, and may be unsuccessful if the magician's luck runs out :)
Performing the trick with a non-standard deck of cards, with any number of suits and any number of cards in each suit, what is the probability of performing a successful magic trick?
Note:
Assume that the deck is shuffled uniformly randomly.
Assume that any suit contains at least two cards, and every suit contains the king card and the queen card.
A suit consists of distinct cards numbered from
1
to
C
, and the cards numbered
1
and
2
are Kings and Queens respectively. Note that any card is uniquely identified by its suit and card number.
Input
The first line contains
T
denoting the number of test cases. Each of the next
T
lines consists of two space-separated integers
S
and
C
, denoting the number of suits and the number of cards in each suit respectively.
Constraints
1 ≤ T ≤ 1692
1 ≤ S ≤ 36
2 ≤ C ≤ 48
Output
For each test case, print the probability of the magician performing a successful magic trick. An
absolute
error less than
10
-6
will be ignored.
Sample Input
2
2 2
2 3
Sample Output
0.333333333333
0.133333333333
Explanation
In the first test case, there are
4
cards in the deck (
2
suits with
2
cards each). This means that there can be
4!
different permutations of the shuffled cards. Only
8
of them contain at least one pair of adjacent Kings and Queens. The probability of a successful magic trick is, therefore,
8/24 = 1/3
Reference
HackerRank - Random Magic | 34,553 |
AND Queries (ANDQQ)
Given an array
A
of
N
integers, you are required to solve
Q
queries. Each query consists of a positive integer
V
and a non-negative integer
K
. For each query, find out how many numbers in the array
A
have exactly
K
common one bits with the number
V
.
In other words, for each query, you need to calculate how many numbers are there in the array such that
A
i
&
V
have exactly
K
bits set in its binary representation, where
&
denotes the
bitwise AND
operation.
Note that since the input can be huge, they will be generated randomly using a pseudorandom generator, whose parameters will be given as input. Also for similar reasons, it is not required to output the result for every query, rather compute the sum of this value for all queries and output this sum. More specifically, for the
i-th
query, let
C
i
be the count of integers in
A
having exactly
K
common one bits with
V
i
. Then it is required to output the sum of all
C
i
only.
Input
The first line contains an integer
T
, denoting the number of test cases. Each test case contains six space separated integers in the order:
seed, N, Q, mod_A, mod_V, mod_K
. Afterwards, the input for each test case will be generated as described by the python code below.
def random():
global seed
seed = (seed * 997 + 29) % 2117566807
return seed
A = [0 for _ in range(N)]
for i in range(N):
A[i] = random() % mod_A
V = [0 for _ in range(Q)]
K = [0 for _ in range(Q)]
for i in range(Q):
V[i] = random() % mod_V
K[i] = random() % mod_K
Note that the
seed
is a global variable which gets updated after each random call, with the initial value being given as input.
Constraints
1 ≤ T ≤ 25
1 ≤ N, Q ≤ 250000
0 ≤ seed < 2117566807
1 ≤ mod_A, mod_V ≤ 250000
1 ≤ mod_K ≤ 19
Output
For each test case, output the case number followed by the required output. Please refer to the sample input/output section for more clarity of the format.
Sample Input
2
1 10 10 4 4 3
0 100 1000 10000 100000 10
Sample Output
Case 1: 26
Case 2: 10260
Explanation
For the first case:
A = [2, 3, 0, 1, 1, 2, 2, 3, 1, 0]
V = [2, 0, 3, 1, 0, 0, 2, 0, 0, 1]
K = [0, 2, 1, 1, 1, 2, 2, 0, 2, 2]
C = [5, 0, 6, 5, 0, 0, 0, 10, 0, 0] | 34,554 |
March Of The King (CHECKMEET)
The white king George lives all alone in a
chessboard
(A standard chessboard consists of
8
rows and columns). He lives alone because the evil black king Andrew killed all the other pieces in frustration after George beat him in a game of chess.
Wandering all alone with no purpose and literally bored to death, King George invented a new game to keep him occupied. King George has a
secret word
in his mind. It is the word he used to shout instead of the usual
checkmate
after beating the black king in a chess game. King George loves to march, so he decided to take a tour through the chessboard. He assigns a single lowercase letter to each square of the chessboard first. He can then start his tour from any square on the chessboard. From a square, the king can move to any neighboring square inside the board as in the game of
chess
. However, it is not allowed to move to the same square twice during the journey. In other words, all the squares visited by the king must be
distinct
.
After completing his tour (the tour can be stopped anytime), George concatenates all the characters in the order of his travel to form a word. Since he has nothing better to do, the white king wants to know how many different ways he can complete the tour so that the secret word is formed afterward.
Two ways are considered different if a different square is visited at any moment. Note that the order in which the squares are visited also matters. As a consequence, for example the path
(1, 2) → (2, 1)
and
(2, 1) → (1, 2)
are considered different.
Formally the problem is as follows:
Let
B(X, Y)
be the lowercase letter assigned to square
(X, Y)
. Also, let the
secret word
be
S
1
S
2
... S
K
.
Your task is to find the number of possible
King's tours
. A King's tour is a sequence of coordinates
(X
1
, Y
1
), (X
2
, Y
2
) ... (X
K
, Y
K
)
satisfying:
1 ≤ X
i
, Y
i
≤ 8
B(X
i
, Y
i
) = S
i
for all 1 ≤ i ≤ K
(X
i
, Y
i
) ≠ (X
j
, Y
j
) for all 1 ≤ i < j ≤ K
max(|X
i
- X
i + 1
|, |Y
i
- Y
i + 1
|) = 1 for all 1 ≤ i < K
Input
The first line of input consists of a single integer
K
denoting the length of the secret word. The next line contains the secret word consisting of
K
lowercase letters. The next
8
lines each contain
8
characters describing the lowercase letters assigned to the chessboard in row-major order.
Constraints
1 ≤ K ≤ 11
Output
Print a single line containing a single integer denoting the number of different tours forming the secret word.
Example
Input:
2
aa
aabbbbbb
aabbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
Output:
12
Input:
9
checkmate
checkmat
checkmee
checkmat
checkmee
checkmat
checkmee
checkmat
checkmee
Output:
7698
Reference
HackerRank - March Of The King | 34,555 |
HowManyLis (HMLIS)
The task is simply to find LIS and number of way we can select distinct LIS
LIS (short for Longest Increasing Subsequence) is the longest subsequence of the sequence in which every element in the subsequence is increasing.
A LIS is distinct when one of the element come from different index of the beginning array.
This task involves finding length of Longest IS and number of ways LIS can be made.
Input
First line: integer
N
represent number of elements in the sequence
N <= 100000
.
Second line:
N
integers represent number in the sequence, each integer is in the range [1, 100000000].
Output
2 integer in 1 line, Length of LIS and Number of LIS that can be made.
The answers can be very large, so print both answers mod 1000000007.
Examples
Input:
5
1 3 2 5 4
Output:
3 4
Input:
5
1 2 5 3 3
Output:
3 3
Explanation
In the first test case, the subsequence are (1, 3, 5), (1, 3, 4), (1, 2, 5), (1, 2, 4).
In the second test case, the subsequence are (1, 2, 5), (1, 2, 3), (1, 2, 3). Note that there are two 3s in the sequence which both count separately. | 34,556 |
Superpowertree (POWTREE)
Ben just learned about range-queries. He was so fascinated of them that he even wanted to create his own problem involving range-queries. He was thinking about the power function: let pow(a, b) = a
b
. But this function was a) too boring and b) not a function over a range. So he just took an array of size n namely a
0
... a
(n - 1)
and defined the superpower of a range:
superpower(l, r) = pow(pow(... pow(pow(a
l
, a
(l + 1)
), a
(l + 2)
) ... a
(r - 1)
), a
r
).
Or more formally:
superpower(x, x) = a
x
superpower(l, r) = pow(superpower(l, r - 1), a
r
) if l != r
He then suddenly realised that his problem also needs updates to be a good query-problem. So he decided to add normal updates of the form "change the number at position k to v". But while trying small values for his arrays, he realized that already the results for these small values were getting really big, so he decided he only wants them modulo m. But as Ben is not as experienced in making problems as in not-listening to his teacher (who is btw. talking about associativity of operations for some data structures right now), he doesn't know that taking prime numbers as modulos is the normal way of doing it. So he just chooses any number m but with the restriction that it's coprime to all the numbers in his array.
Suddenly he realised that the problem invented by himself was too difficult for him to solve as his own solution didn't work. Help Ben!
Input
On the first line, there are three numbers n, q, m: the size of the array, the number of queries and the number for the modulo.
Then on the second line, n numbers follow: a
0
, a
1
, ..., a
(n - 1)
Then each each of the next q lines consists of a char and two numbers:
if the char is q, then the two numbers l and r follow: Ben wants to know superpower(l, r) modulo m.
if the char is u, then the two numbers k and v follow: Ben wants to update a
k
to v.
Output
For each query of type q, output the superpower of the range modulo m.
Constraints
1 <= n, q <= 1e5
2 <= m <= 1e15
At any time, all the values in the array are <= 1e9 and are coprime to m.
Edit (6.5.2020):
I know that with m <= 1e15, there may be overflows if not handled correctly. In C++ in gcc, there is the __int128 type which is essentially a 128-bit integer. The master solution uses __int128 everywhere, so you can use it without running into TLE.
Example
Input:
10 10 77
2 6 3 9 5 4 8 3 4 5
q 0 9
q 3 6
q 2 7
u 1 4
u 4 9
q 0 8
q 4 7
q 4 8
u 5 5
q 2 7
2 6 3 9 5 4 8 3 4 5
q 2 7
Output:
1
23
1
36
64
71
1 | 34,557 |
Trailing Zeros (ALIEN0)
There's a line of
N
numbers where each number is a positive integer that is less than
10
9
. Every second, an alien comes down to the Earth and ask a certain problem. "How many zeros are there after all the other digits when you multiply all the number in range
L
and
R
?". Unfortunately, the alien don't know base 10 numbers. In fact, there're
6
species of alien in the UFO, the first species use base-1 number, second use base-2 and so on. (Yes, the first species do not exist, and therefore will not come down to the Earth).
You are given a task to answer the aliens' questions in their numerical system for a day, which mean there're up to
100,000
questions to be answer.
Input
First line,
N <= 100000
which is mentioned above
and
Q <= 100000
representing number of questions.
Next line,
N
positive integers
on the line on earth, each not exceeding
10
9
.
Next
Q
lines,
1 <= L <= R <= N
representing a range each alien mentioned, and
2 <= S <= 6
representing the alien species.
Output
Q lines,
each line is a number represent the answer for each alien.
Example
Input:
5 3
2 3 6 5 100
1 5 2
1 3 6
1 2 3
Output:
4
2
1 | 34,558 |
PermRLE (GCJ08RND2PD)
You've invented a slight modification of the run-length encoding (RLE) compression algorithm, called PermRLE.
To compress a string, this algorithm chooses some permutation of integers between 1 and k, applies this permutation to the first k letters of the given string, then to the next block of k
letters, and so on. The length of the string must be divisible by k. After permuting all blocks, the new string is compressed using RLE, which is described later.
To apply the given permutation p to a block of k letters means to place the p[1]-th of these letters in the first position, then p[2]-th of these letters in the second position, and so on.
For example, applying the permutation {3,1,4,2} to the block "abcd" yields "cadb". Applying it to the longer string "abcdefghijkl" in blocks yields "cadbgehfkilj".
The permuted string is then compressed using run-length encoding. To simplify, we will consider the compressed size of the string to be the number of groups of consecutive equal letters. For example, the compressed size of "aabcaaaa" is 4; the first of the four groups is a group of two letters "a", then two groups "b" and "c" each containing only one letter, and finally a longer group of letters "a".
Obviously, the compressed size may depend on the chosen permutation. Since the goal of compression algorithms is to minimize the size of the compressed text, it is your job to choose the permutation that yields the smallest possible compressed size, and output that size.
Input
The first line of input gives the number of cases, N. N test cases follow.
The first line of each case will contain k. The second line will contain S, the string to be compressed.
N = 20 S will contain only lowercase letters 'a' through 'z' The length of S will be divisible by k
2 <= k <= 16 1 <= length of S <= 50000
Output
For each test case you should output one line containing "Case #X: Y" (quotes for clarity) where X is the number of the test case and Y is the minimum compressed size of S.
Example
Input:
2
4 abcabcabcabc
3 abcabcabcabc
Output:
Case #1: 7
Case #2: 12 | 34,559 |
Boba Inversion (BOBAINV)
Topuch is the name of the brand new bubble tea shop just opened on your street. Just for a bubble tea lover like you :3
Touch and Top, the owners of the shop, think that the tea that comes after and have less sweetness than the previous one is unique. So they would consider the pair of tea that is unique as having the uniqueness value of 1. You've just finished reading the shop description and suddenly, a cute girl in pink come up to you and ask you if you can calculate the uniqueness of the range of the tea sequence for her. You have to help help her... :3
The uniqueness in range
L...R
is defined by the number of the pair of
(i, j) L ≤ i ≤ j ≤ R
that the sweetness of tea at
i
is higher than the one at
j
.
Input
The first line contains a single number
N
denoting the size of the tea sequence.
(1 ≤ N ≤ 5000)
The second line contains
N
numbers;
Ai
denoting the sweetness of each tea.
(1 ≤ Ai ≤ 1e9) (1 ≤ i ≤ N)
The third line contains a single number
M
denoting the number of question the girl want to ask you.
(1 ≤ M ≤ 1e6)
The next
M
lines each contain two numbers;
L R
meaning that the question asks about the sum of uniqueness of the all tea that is in range index
L
to
R
.
(1 ≤ L ≤ R ≤ N)
Output
M
lines each contain a single number;
Bj
denoting the answer for the question
j
.
Example
Input:
8
3 5 6 2 4 5 7 1
5
1 3
2 4
2 5
1 8
4 7
Output:
0
2
4
13
0 | 34,560 |
Submatrix Sum of a Sparse Matrix (BUZZ95)
You are given a sparse matrix of dimensions N x M. There K cells in the matrix {(x1, y1), (x2, y2) ... (xK, yK)} with non-zero values {v1, v2 ... vK}. All the other cells except these K cells contain value = 0. You are asked Q queries of the form sx sy fx fy, you need to print the sum of submatrix bounded by (sx, sy) and (fx, fy).
Input
First line contains two space separated integers N, M. (1 ≤ N, M ≤10
9
)
Second line contains the integer K (1 ≤ K ≤ 10
5
)
Next K lines contain three space separated integers xi, yi, vi. (1 ≤ xi ≤ N, 1 ≤ yi ≤ M, 1 ≤ vi ≤ 10
9
).
Next line contains Q. (1 ≤ Q ≤ 10
5
)
Next Q lines contain four space separated integers sx, sy, fx, fy. (1 ≤ sx ≤ fx ≤ N, 1 ≤ sy ≤ fy ≤ M).
Output
For each query, print a single integer representing the sum of submatrix.
Example
Input:
10 10
2
1 1 5
2 2 15
1
1 1 3 3
Output:
20 | 34,561 |
Recursive Sequence (Version III) (SPP3)
Sequence
(a
i
)
of natural numbers is defined as follows:
a
i
= b
i
if
i ≤ k
a
i
= c
1
a
i-1
+ c
2
a
i-2
+ ... + c
k
a
i-k
if
i > k
where
b
j
and
c
j
are given natural numbers for
1
≤ j
≤
k
. Your task is to compute
a
2
m
+
a
2
m+1
+
a
2
m+2
+ ... +
a
2
n
for given
m
≤
n
and output it modulo a given positive integer
p
(not necessarily prime).
Input
On the first row there is the number
T
of test cases (
T
≤
50).
Each following test case contains four lines:
k
- number of elements of
(c)
and
(b)
(
1
≤
k
≤
15
)
b
1
... b
k
-
k
natural numbers where
0
≤
b
j
≤
10
9
separated by spaces
c
1
... c
k
-
k
natural numbers where
0
≤
c
j
≤
10
9
separated by spaces
m
,
n
,
p
- natural numbers separated by spaces (
1
≤
m
≤
n
≤
10
18
,
1
≤
p
≤
10
8
)
Output
Exactly
T
lines, one for each test case: (
a
2
m
+
a
2
m+1
+
a
2
m+2
+ ... +
a
2
n
) modulo
p
.
Example
Input:
2
3
2 3 5
1 2 3
10 15 1000000
15
401 131 940 406 673 592 532 452 733 966 602 600 61 212 257
13 12 81 75 37 12 10 35 25 75 16 90 27 33 47
2 85704376 99999991
Output:
248783
32397016
Note
You can try the problem
SPP
first. | 34,562 |
Dinostratus Matrices (DINOMAT)
Let's call a matrix
A[3 × 3]
Dinostratus if all its nine elements are different positive integer numbers and each its element
a
i,j
(where 1 ≤
i
,
j
≤ 3) is a multiple of its neighbors
a
i-1,j
,
a
i-1,j-1
and
a
i,j-1
(if they exist). In other words the following conditions hold:
a
i,j
=
X
·
a
i-1,j
for some positive integer
X
(if
i
≥ 2)
a
i,j
=
Y
·
a
i,j-1
for some positive integer
Y
(if
j
≥ 2)
a
i,j
=
Z
·
a
i-1,j-1
for some positive integer
Z
(if
i
,
j
≥ 2)
For example the matrices
1
3
9
2
6
18
4
12
36
3
18
198
21
126
4158
147
882
29106
10
100
4000
50
1000
20000
10000
100000
1000000
are Dinostratus. And the following matrices are not:
1
3
9
2
6
18
4
12
54
1
2
4
2
4
8
4
8
16
36
12
4
18
6
2
9
3
1
Let's define the element
a
3,3
of a Dinostratus matrix
A[3 × 3]
as a
base number
. Given a base number, find out how many different Dinostratus matices exist. Two matrices
A
and
B
are different if there are such indexes
i
,
j
that
a
i,j
≠
b
i,j
.
Input
Input file consists of several test cases. Input file starts with a line containing an integer
T
(
T
≤ 500), which is the number of test cases. The next
T
lines constain one base number
N
(1 ≤
N
≤ 1000000).
Output
For each test case output a single line containing the number of different Dinostratus matrices corresponding to the base number. It is guaranteed that the answer is less than 2
63
.
Example
Input:
7
1
10
100
1000
10000
100000
1000000
Output:
0
0
2
2382
257110
7475718
106889830
Note
You can try the problem
DINONUM
first. | 34,563 |
Kingdom of Equality (KEQUALITY)
There is a kingdom called DomKi. There are
N
cities and
N – 1
bidirectional roads in DomKi. The cities of DomKi are connected to each other in such a way that it forms a
Tree
.
Recently a dangerous virus called corona has attacked the kingdom and the people in several cities are affected by the disease COVID-19 (which is caused by the corona virus). The infection of the virus has been declared as an epidemic in DomKi.
As COVID-19 - spreads from person to person in close proximity, similar to other respiratory illnesses, such as the flu, some cities in DomKi are under lockdown to ensure social distancing. Due to lockdown, some roads also became unavailable to use.
Now there is a group of people who may stay in different cities. For an important issue they all want to meet in a specific city if possible. But there is a strange rule is followed by them. They all want to choose a city in such a way that the selected city is reachable by all of them and everyone has to travel the same distance from their residence city to the selected city through the shortest path.
The distance between two cities in DomKi is the number of roads between them in the shortest path.
Suppose there are 10 cities in DomKi numbered from 1 to 10 and 9 roads shown in the above picture. The number (
0 or 1
) associated with each road determines whether this road is available or not (
Note that, 0 means the road is not available and 1 means available
.)
Let there be a group of
2
people, one each in cities
4
and
6
, who want to meet. Then there is a possible set (say
S
) of
4
different cities they can select, which is,
S = {2, 1, 3, 7}
. The shortest distance from city
4
to each city in
S
and city
6
to each city in
S
is
identical
. (
Note cities 5, 9 and 10 are also the same distance away from cities 4 and 6 but they are not reachable
.)
Now the task is to count the size of the set
S
for a given group of people.
It is to be observed that a group may consist of only 1 person.
Input
The first line of the input contains a positive integers
N
, denotes the number of cities in the kingdom.
The next
N - 1
lines contains the description of the roads.
Each road is described by three positive integers
u, v, k
, where
u
and
v
denotes two cities which is connected by this road and
k
denotes the availability of the road (
0
or
1
).
The next line contains a positive integer
Q
, denotes the number of query.
Each of the next
Q
lines will describe a group of people, which is a query to be answered. Each line will begin with a positive integer
g
i
, which denotes the number of people in the
i
th
group. Then in the same line
g
i
space separated numbers will be given which denotes the cities where the people of this group reside.
Note, that there can be more than one person in each city
.
1 ≤ N, Q, u, v ≤ 2 × 10
5
.
u ≠ v
.
1 ≤ u, v ≤ N
0 ≤ k ≤ 1
1 ≤ g
i
≤ 2 × 10
5
Sum of all g
i
≤ 2 × 10
5
.
Output
For each query output
the size of the set S
in a new line which is described in the problem statement.
Example
Input:
10
1 2 1
1 3 1
3 7 1
2 4 1
2 6 1
2 5 0
5 9 1
5 10 1
4 8 1
1
2 4 6
Output:
4 | 34,564 |
Acronym (ACRYM)
An acronym is made of up the initial letter(s) of the words in a phrase, such as EU (European Union) and BREXIT (BRitish EXIT). In this problem, we can also either ignore or consider the conjunction "
and
", and the following adpositions "
in
", "
on
", "
at
", "
to
", "
of
", "
from
", "
for
" and "
with
" when making the acronym, such as BENELUX (BElgium, NEtherlands and LUXembourg) and RADAR (RAdio Detection And Ranging).
Given an acronym
A
, and a list of
N
strings
W
1
,
W
2
...
W
N
, you would like to find out the number of possible combinations of making the given acronym by using all the N strings following their order. That is, the acronym must be made up of at least one initial letter of each word, except the above-mentioned conjunction and adpositions (either skip or use it). Both A and the N strings only consist of lowercase latin letters.
Input
The first line is the number of test cases
T
. (1 ≤ T ≤ 20)
For each test case, it starts with one integer
N
. (1 ≤ N ≤ 200)
Next line is a string
A
. (1 ≤ |A| ≤ 10
4
)
Following N lines, each consisting of one string
W
i
. (1 ≤ |W
i
| ≤ 50)
It is guaranteed that W
1
is neither conjunction nor adposition.
Output
Output one integer indicating the number of possible combinations.
Example
Input:
3
3
duckhim
duck
hello
moto
7
natiofforessaa
national
office
for
forest
safety
in
aachen
4
whiskey
what
is
secret
key
Output:
0
4
1
Explanation
In case 1, no combination is possible.
In case 2, there are four possible combinations:
NATI
onal
OF
fice for
FORES
t
SA
fety in
A
achen
NATI
onal
OF
fice for
FORES
t
S
afety in
AA
chen
NATI
onal
O
ffice
F
or
FORES
t
SA
fety in
A
achen
NATI
onal
O
ffice
F
or
FORES
t
S
afety in
AA
chen
In case 3, only one possible combination exists:
WH
at
I
s
S
ecret
KEY | 34,565 |
Modulo Sequence (MODSEQ)
Nevest has a sequence
A
with
N
distinct elements. She wants to have a sequence
S
with length
M
and all of the conditions below must be fulfilled:
For all subarrays in
S
of length
K
, the sum of each number in the subarray must be divisible by
K
.
For
1 ≤ i < j ≤ M
,
S
i
≠ S
j
must hold.
A
must be a subsequence of
S
.
For
1 ≤ i ≤ M
, constrain
1 ≤ S
i
≤ 5 × 10
5
must be fulfilled.
The length of sequence
S
mustn't exceed
5 × 10
5
.
Nevest is not very good at problem-solving so she asked you instead. Help Nevest by giving her any valid sequence or print "-1" if no valid sequence exist (without quotation marks).
Please note that you don't have to minimize M.
Input Format
N K
A
1
A
2
... A
N
Output Format
If there's a valid answer, print
M
in the first line followed by a line containing sequence
S
with
M
numbers. If there's no valid sequence
S
print "-1" (without quotation marks).
Sample Input 1
5 3
1 3 2 5 4
Sample Output 1
7
1 3 2 7 9 5 4
Sample Input 2
4 2
1 3 5 7
Sample Output 2
4
1 3 5 7
Constraints
1 ≤ K ≤ N ≤ 500
1 ≤ A
i
≤ 500
A
i
≠ A
j
, for 1 ≤ i < j ≤ N | 34,566 |
Balls and Queries (QBALL)
Xima has
N
balls arranged together in a line, the
i
-th
(1 ≤ i ≤ N)
ball has a value of
A
i
.
Tzaph asks
Q
queries to Xima. There are two types of queries:
1 i k
: The value of the
i
-th ball is changed into
k
. In other words,
A
i
= k
.
Take note that A
i
and k could have a same value. In this case, Xima shouldn't do anything
.
2 i
: Tzaph removes the
i
-th ball out from the line. Print the number of pairs
(x, y)
such that the
x-th
and the
y-th
ball is in the line,
x < y
, and
A
x
= A
y
. After this query, Tzaph returns the
i
-th ball back to the line in its original position.
However, Tzaph asks too many queries and Xima has too many balls. Xima asks you to help him answer all of Tzaph's queries. Help him out!
Input
The first line contains two integers
N
and
Q
.
The second line consists of
N
integers, where the
i
-th integer represents
A
i
.
The next
Q
lines represents the queries with format explained in the description.
Output
For every second type of query, print the answer required.
Constraints
1 ≤ N, Q, A
i
, k ≤ 10
5
Examples
Input 1:
5 5
1 2 3 4 5
1 2 3
1 5 4
2 1
1 2 4
2 4
Output 1:
2
1
Input 2:
1 3
1
2 1
1 1 3
2 1
Output 2:
0
0 | 34,567 |
Weird Construction (KONSTRAKSCHION)
Vieri Corp, a technology company, has requested Bima, a constructor, to build an isosceles triangle on their brand new field. On each vertex of the triangle, they requested a pole
A, B
and
C
where
AB
=
BC
.
It is guaranteed that B is the shortest pole
. They also requested a rope of length
x
and
y
to connect the tip of the poles
AB
and
BC
respectively. Given the height of pole
A
,
C and the length of rope
x
and
y
help Bima calculate the the height of pole
B
.
You should minimize B. I've decreased the constraints so don't worry about precision error :) It is guaranteed that there will be an answer. The ropes cannot be loose. The pole's diameter is negligible
.
Refer to the image below for better understanding.
Input
A C x y
Output
The height of pole
B
correct to 3 decimal places.
Examples
Input 1:
10 20 10 18.973665961
Output 1:
2.000000
Input 2:
10 7 8.5 6.0207972894
Output 2:
2.500
Constraints
1 ≤ A ≤ 500000
1 ≤ C ≤ 500000
1 ≤ x ≤ 500000
1 ≤ y ≤ 500000 | 34,568 |
Colored Development (BANSTAND)
There are
N
unique colors in the universe, numbered from
1
to
N
. George Michael wants to create a rainbow using these colors. The rainbow will consist of exactly
M
layers. For each layer, George Michael selects a color uniformly randomly from the
N
colors and colors the layer with it.
George Michael wonders what will be the expected number of distinct colors in the rainbow after all the layers are colored in this way.
Input
The first line of the input contains an integer
T
, denoting the number of test cases. Each of the next
T
lines will contain two integers,
N
and
M
.
Constraints
1 ≤ T ≤ 10
1 ≤ N, M ≤ 2 * 10
5
Output
For each test case, print the case number and the expected number of distinct colors in the rainbow after all the layers are colored. Formally, let the expected number of distinct colors be an irreducible fraction
P / Q
. Then you need to print
(P * Q
-1
)
modulo
1000000007
, where
Q
-1
is the modular inverse of
Q
modulo
1000000007
. You may safely assume that there will be a unique modular inverse of
Q
modulo
1000000007
.
Sample Input
3
1 1
2 2
4 2
Sample Output
Case 1: 1
Case 2: 500000005
Case 3: 750000007
Challenge
Too easy? Try the harder version here:
Development Colored | 34,569 |
Development Colored (STANDBAN)
There are
N
unique colors in the universe, numbered from
1
to
N
. George Michael wants to create a rainbow using these colors. The rainbow will consist of exactly
M
layers. For each layer, George Michael selects a color uniformly randomly from the
N
colors and colors the layer with it.
George Michael wonders what will be the probability that there will be at least
K
distinct colors in the rainbow after all the layers are colored in this way.
Input
The first line of the input contains an integer
T
, denoting the number of test cases. Each of the next
T
lines will contain three integers,
N
,
M
and
K
.
Constraints
1 ≤ T ≤ 20
1 ≤ N, M, K ≤ 2 * 10
5
Output
For each test case, print the case number and the probability that the rainbow will contain at least
K
distinct colors after all the layers are colored. Formally, let this probability be an irreducible fraction
P / Q
. Then you need to print
(P * Q
-1
)
modulo
1000000007
, where
Q
-1
is the modular inverse of
Q
modulo
1000000007
. You may safely assume that there will be a unique modular inverse of
Q
modulo
1000000007
.
Sample Input
3
1 1 1
2 2 2
4 2 2
Sample Output
Case 1: 1
Case 2: 500000004
Case 3: 750000006
Challenge(!)
Colored Development | 34,570 |
The Attack Titan (RKRCTAN)
Mikasa always wants to protect Eren at any cost. Even when Eren transforms into his “Attack Titan” form. The country where Mikasa and Eren live is surrounded by a rectangular wall named “Wall Maria” of size A × B where A is the length and B is the width of the wall. There’s another rectangular wall within Wall Maria named “Wall Sina” of size C×D where C is the length and D is the width of the wall. Mikasa knows Eren is fighting with some mindless Titans somewhere between Wall Maria and Wall Sina.
Now, Mikasa wants to reach Eren and fight alongside him. But, She doesn’t know how much area she has to search in order to find Eren. Since, Mikasa has only one talent which is killing Titans mercilessly, She needs your help to find the total area between Wall Maria and Wall Sina. Help her to find Eren.
Input
Input starts with an integer T (≤ 100000), denoting the number of test cases. Each of the next T lines contains 4 integers A, B, C, D (1 ≤ A, B, C, D ≤ 10
18
, C ≤ A, D ≤ B) indicating the length and width of the outer Wall, the length and width of the inner Wall.
Output
For each case print the area which lies between Wall Maria and Wall Sina. Since the answer could be very big, print it modulo 1000000007.
Sample
Input:
6
4 5 2 3
10 20 2 4
10 20 10 20
7 8 7 7
2 2 1 1
1000000000000000000 1000000000000000000 1 1
Output:
14
192
0
7
3
2400 | 34,571 |
Anti Hash (AHASH)
Given a base
B
and a modulus
M
, the polynomial hash of a string
S
, consisting of only lowercase letters
(a-z)
is defined as below:
int Hash(string S, int B, int M){
long long H = 0;
for (int i = 0; i < S.length(); i++){
H = (H * B + S[i] - 'a' + 1) % M;
}
return H;
}
In other words, first the letters of the string are replaced by numbers (equivalent to their position,
'a'
gets mapped to
1
,
'b'
to
2
, ... and
'z'
to
26
). This is then considered to be a number in base
B
(rightmost number is the least significant digit), and the value of this number in
base 10
modulo
M
is called the polynomial hash of the string.
Limak the bear loves to hack other contestants in Codeforces. After the recent educational round, he came to know that his friend Swistak used the polynomial hash function stated above to solve the hardest problem! And believe it or not, he was the only one to solve that problem! Limak is so angry, how can Swistak solve a problem which Limak himself couldn't solve? And worst of all, Swistak used hashing to solve that problem! Limak believes people who uses hashing have no real skill, getting
Accepted
just implies getting lucky, nothing more!
Later that night, Limak realized that he can hack the solution if he is able to solve the following problem efficiently. Limak felt triumphant, he will teach Swistak and that stupid hash function of his a lesson! But Limak is just a little bear, he is not very good at solving problems. Please help Limak solve the following problem so that he can hack Swistak's solution.
Limak will give you a string
S
of length
N
, consisting of only lowercase letters, a base
B
and a modulus
M
. Your task is to find another string
T
, satisfying all of the following constraints:
Length of
T
is exactly
N
T
consists of only lowercase letters
(a-z)
T
and
S
are two different strings
T
and
S
have the same hash, i.e.
Hash(S, B, M) = Hash(T, B, M)
Input
The first line contains
Q
, denoting the number of test cases. Each test case consists of two lines. The first line of each case contains three integers,
N, B, M
. The next line contains the string
S
of length
N
, consisting of only lowercase letters.
Constraints
1 ≤ Q ≤ 30
10
5
≤ N ≤ 10
6
10
5
≤ B < 2
31
10
5
≤ M < 2
31
Si ∈ {a-z}
B ≠ M and both B and M are prime numbers
Output
For each test case, output the string
T
in a single line. It is guaranteed that such a string will always exist for the given constraints. If there are many solutions, you can output any of them.
Sample Input
1
38 666666667 1000000009
bbababbbbbbbaabaababaabbababbababababb
Sample Output
hisotomeseemslikeanotoriouscoincidence
Note
The sample input contains a string of length 38 only for demonstration and clarity. There will be no such cases in the judge data, every case will strictly satisfy the constraints mentioned above.
Challenge
You might also enjoy:
Anti Hash II
The Revenge Of Anti Hash | 34,572 |
Recurrence Power Sum (RECPWSUM)
You are given a series defined by the following recurrence:
f
0
= x, f
1
= y
f
n
= a * f
n-1
+ b * f
n-2
You are required to find the summation of the following series:
f
0
k
+
f
1
k
+
f
2
k
+ ... +
f
n
k
The values
a
,
b
,
x
,
y
,
n
,
k
will be provided. Since the answer can be large, output it modulo
1000000007
.
Input
The first line contains a single integer
T
denoting the number of test cases. Each test case consists of
six
space separated integers on a single line, in the order:
a
,
b
,
x
,
y,
n,
k
.
Output
For each test case, output a single integer (on a separate line) denoting the summation of the series as mentioned above.
Constraints
1 ≤ T
≤ 500
0
≤
a, b
≤
100
0
≤
x, y
≤
10
9
0
≤ n
≤ 10
15
0
≤ k
≤ 1000
Example
Input:
4
1 1 0 1 3 0
1 1 0 1 3 1
1 1 0 1 4 2
1 1 0 1 4 3
Output:
4
4
15
37
Explanation
In all the sample test cases,
f
0
= 0, f
1
= 1, f
n
= f
n-1
+ f
n-2
, which is the regular
Fibonacci
series. The first few terms of the sequence are
0, 1, 1, 2, 3, 5, ...
.
For the first case, the required sum is
0
0
+ 1
0
+ 1
0
+ 2
0
= 4.
For the second case, the required sum is
0
1
+ 1
1
+ 1
1
+ 2
1
= 4
.
For the third case, the required sum is
0
2
+ 1
2
+ 1
2
+ 2
2
+ 3
2
= 15
.
For the fourth case, the required sum is
0
3
+ 1
3
+ 1
3
+ 2
3
+ 3
3
= 37
.
Note
: Time limit is set leniently to allow slow languages to pass. | 34,573 |
Acronym II (ACRYM2)
An acronym is made of up the initial letter(s) of the words in a phrase, such as EU (European Union) and BREXIT (BRitish EXIT). In this problem, we can also either ignore or consider the conjunction "
and
", and the following adpositions "
in
", "
on
", "
at
", "
to
", "
of
", "
from
", "
for
" and "
with
" when making the acronym, such as BENELUX (BElgium, NEtherlands and LUXembourg) and RADAR (RAdio Detection And Ranging).
Given an acronym
A
, and a list of
N
strings
W
1
,
W
2
...
W
N
, you would like to find out the number of possible combinations of making the given acronym by using all the N strings following their order. That is, the acronym must be made up of at least one initial letter of each word, except the above-mentioned conjunction and adpositions (either skip or use it). Both
A
and the
N
strings only consist of lowercase latin letters. Since the answer can be large, output the answer modulo
1000000007
.
Note
: This is a harder version of the problem
ACRYM
, with larger constraints. Please read the input section carefully.
Input
The first line is the number of test cases
T
. (1 ≤ T ≤ 20)
For each test case, it starts with one integer
N
. (1 ≤ N ≤ 200)
Next line is a string
A
. (1 ≤ |A| ≤ 50000)
Following N lines, each consisting of one string
W
i
. (1 ≤ |W
i
| ≤ 250)
It is guaranteed that W
1
is neither conjunction nor adposition.
Output
Output one integer indicating the number of possible combinations.
Example
Input:
3
3
duckhim
duck
hello
moto
7
natiofforessaa
national
office
for
forest
safety
in
aachen
4
whiskey
what
is
secret
key
Output:
0
4
1
Explanation
In case 1, no combination is possible.
In case 2, there are four possible combinations:
NATI
onal
OF
fice for
FORES
t
SA
fety in
A
achen
NATI
onal
OF
fice for
FORES
t
S
afety in
AA
chen
NATI
onal
O
ffice
F
or
FORES
t
SA
fety in
A
achen
NATI
onal
O
ffice
F
or
FORES
t
S
afety in
AA
chen
In case 3, only one possible combination exists:
WH
at
I
s
S
ecret
KEY | 34,574 |
Anti Hash II (AHASH2)
Given a base
B
and a modulo
M
, the polynomial hash of a string
S
consisting of only lowercase letters is defined as below.
Let
S = S
0
S
1
…S
N-1
be a string of length
N
containing only the lowercase letters (
a-z
).
Hash(S) = ∑ B
N-i-1
× D(S
i
) % M
D(S)
= Lexicographical position of character
S
among the letters
a-z
, indexed from
0
.
D(a) = 0, D(b) = 1 ... D(z) = 25
.
In other words, first the letters of the string are replaced by numbers (equivalent to their position). This is then considered to be a number in base
B
, and the value of this number in
base 10
modulo
M
is called the polynomial hash of the string.
Calculating the hash of a string using the above method seems easy enough. What about the opposite? You are given a base
B
, a modulo
M
, a positive integer N
, and a hash value
H
. Calculate how many strings are there such that their hash is equal to
H
, consisting of only lowercase letters and their length not exceeding
N
. Since the answer can be rather huge, output it modulo
10
9
+ 7 (1000000007)
.
Input
The first line contains an integer
T
, denoting the number of test cases. Each test case starts with four integers
B, M, N, Q
. The numbers
B, M, N
denotes the base, modulus and the maximum length of any string as stated above. The number
Q
indicates the number of queries. Each of the next
Q
lines contain a single integer, denoting
H
, the required hash value.
Constraints
1 ≤ T ≤ 150
26 ≤ B ≤ 30000
1 ≤ M, N ≤ 30000
1 ≤ Q ≤ 300
0 ≤ H < M
For 95% of the test cases, B, M, N ≤ 300
Output
For each case, first output a line of the format
Case X:
, where
X
is the case number, starting from
1
. And then, for each query, output the number of different strings with the given hash value modulo
10
9
+ 7 (1000000007)
in a single line.
Print a blank line after every test case.
Example
Input:
3
26 97 2 3
0
1
96
147 147 147 3
0
10
100
100 110 120 1
35
Output:
Case 1:
8
8
6
Case 2:
944164777
944164777
0
Case 3:
110169522
Challenge
You might also enjoy:
Anti Hash
or
The Revenge Of Anti Hash
. | 34,575 |
Breaking Math (BBAD)
Walter is a high school chemistry teacher. After being diagnosed with stage 3A, inoperable lung cancer, Walter is devastated. Realizing he does not have much time left, a desperate Walter resorts to cooking crystal methamphetamine, in order to provide for his treatment and family. And guess what, he mixes up with some really horrible people in the process.
The worst of them is Heisenburg, a badass physicist and the ultimate drug lord. Walter needs Heisenburg’s active support to distribute the methamphetamine he produces. Alas, Heisenburg is a cautious man. Heisenburg is initially skeptical about Walter, and decides to give the following problem to Walter in order to prove his worth.
w(n)
is defined to be the number of distinct prime factors of
n
, for example:
w(1) = 0, w(2) = 1, w(3) = 1, w(4) = 1, w(5) = 1, w(6) = 2, w(30) = 3
f(n, k) = ∑ k
w(i)
where
1 ≤ i ≤ n
For instance,
f(6,2) = 2
w(1)
+ 2
w(2)
+ 2
w(3)
+ 2
w(4)
+ 2
w(5)
+ 2
w(6)
= 13
Given
n
and
k
, calculate
f(n, k)
.
Input
The first line contains an integer
t
, denoting the number of test cases. Each of the next
t
lines contains two integers,
n
and
k
, separated by a single space. Sum of
n
will not exceed
10
11
in an input file.
Constraints
1 ≤ t ≤ 100
1 ≤ n ≤ 10
11
1 ≤ k ≤ 10
1 ≤ ∑n ≤ 10
11
Output
For each case, output a line of the format
Case X: Y
, where
X
is the case number, starting from
1
, and
Y
is the required answer. You can safely assume that the answer will fit in a
signed 64 bit integer
.
Sample Input
10
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
Sample Output
Case 1: 1
Case 2: 3
Case 3: 7
Case 4: 13
Case 5: 21
Case 6: 61
Case 7: 85
Case 8: 113
Case 9: 145
Case 10: 271 | 34,576 |
Shuffling Problem (SHP)
You are given an unordered array with n
distinct
numbers from 1 to n. You have to perform
exactly
k swaps and print the lexicographically largest array that can be obtained.
In one swap, you can choose any two
distinct
indices and swap the elements at those indices.
Input
First line consists of 2 integers n (1 < n ≤ 100000) and k (0 ≤ k ≤ 10
9
).
Next line consists of n integers (a
0
, a
1
... a
n-1
).
Output
You have to print lexicographically largest array obtained.
Example
Input:
5 2
1 2 4 3 5
Output:
5 4 2 3 1 | 34,577 |
Base Exploration (BSEXP)
Problem Statement is easy, for a given number
N
, you have to print the
base B
such that if we write
N
in base
B
then it would contain most 0's at the end.
If more then one such
base
exist, which satisfy the given condition then print the smallest such base.
Input
The first line of the input consist of a single integer number
t
which determines the number of tests.
In each of next
t
lines there is a single integer number
N
.
Constraints
0 < t ≤ 10
5
2 ≤ N ≤ 10
12
Output
Output contains one line with one integer
B
such that
N
written in base
B
has the most zeros at the end and is the smallest
B
with this property.
Example
Input:
2
72
18
Output:
2
3
Explanation
The answer for N=72 is B=2, because 72=1001000
2
(72 written in base 2) has 3 zeros at the end.
Using base 3, we only get 2 zeroes at the end (because 72=2200
3
),
using base 6 would also give us 2 zeros, and no other base would give us more than 1 zero
For 18, 18=10010
2
and 18=200
3
so answer will be 3.
Note:
Test case were regenerated on 23 June 2020.
As rejudge is disabled by SPOJ please submit your code again. | 34,578 |
Personal LCM (PRLCM)
We have an integer sequence of length N: A
0
, A
, ... A
N−1
.
Find the following sum:
$\displaystyle\sum^{N-2}_{i=0}{\sum^{N-1}_{j=i+1}{lcm(Ai, Aj)}}$
(Note: lcm(a, b) denotes the least common multiple of a and b)
Since the answer may be enormous, compute it modulo 998244353
Constraints
1 ≤ N ≤ 2 * 10
5
1 ≤ A
≤ 10
6
All values in input are integers.
Input
First line of input will be consist of a single N, number of elements.
In next line you will get N space separated integers: A
0
A
1
A
2
A
3
A
4
... A
N-1
Output
Print the sum modulo 998244353.
Example
Input:
3
2 4 6
Output:
22
Explanation
lcm(2, 4) + lcm(2, 6) + lcm(4, 6) = 4 + 6 + 12 = 22. | 34,579 |
A Summatory (Extreme) (ASUMEXTR)
f(n) is defined as: f(n) = 1
k
+2
k
+3
k
+...+n
k
, so it is the sum of the k-th power of all natural numbers up to n.
In this problem you are about to compute,
f(1) + f(2) + f(3) + ... + f(n)
Note
: This is a harder version of the problem
ASUMHARD
, with larger constraints. Please read the constraints section carefully.
Input
The first line is an integer
T
, denoting the number of test cases. Then,
T
test cases follow.
For each test case, there are two integers
n
and
k
written in one line, separated by space.
Output
For each test case, output the result of the summatory function described above.
Since this number could be very large, output the answer modulo
1,234,567,891
.
Example
Input:
5
2 3
10 3
3 3
100 0
100 1
Output:
10
7942
46
5050
171700
Explanation
In case 1,
n
= 2,
k
= 3. f(1) = 1
3
, f(2) = 1
3
+2
3
.
ans
= f(1) + f(2) = 10.
Constraints
Overall constraints
5 ≤
T
≤ 500000
1 ≤
n
≤ 10
18
0 ≤
k
≤ 10000000
More precise information (there are 6 test files):
Test #0:
T
= 500000, 0 ≤
k
≤ 100
Test #1:
T
= 50000, 0 ≤
k
≤ 1000
Test #2:
T
= 5000, 0 ≤
k
≤ 10000
Test #3:
T
= 500, 0 ≤
k
≤ 100000
Test #4:
T
= 50, 0 ≤
k
≤ 1000000
Test #5:
T
= 5, 0 ≤
k
≤ 10000000
It should be clear from the constraints that an
O(k
2
)
solution
will
not pass
. Inputs are generated uniformly randomly in the given ranges (with some manual worst case inputs). Time limit is set to 2x of my unoptimized C++ code. | 34,580 |
Birthday Present (HBD)
Today is problem setter's best friend Jenny’s birthday. Long ago, Jenny, being a very clever girl, asked the problem setter to perform some queries on a tree but he couldn’t do it. Now, he seeks your help to impress her on her birthday by answering those queries.
Recall that a tree is a connected acyclic undirected graph with
n
nodes and
n-1
edges. In each node there are some flowers. The two type of queries are described as:
1 u v x
2 u y
For first type, you have to calculate the minimum number of vertices needed to be visited on the path from
v
to
u
, starting at
v
, to collect at least
x (1 ≤ x ≤ 10
18
)
flowers, where
v
is a descendant of
u
.
Note that you cannot visit any node that is not in the path from v to u and you cannot skip any node of the path from v to that node you've chosen at last.
If it's impossible to collect at least
x
flowers visiting all the vertices from
v
to
u
then you have to print
-1
.
For second type, you have to add y
(y can be negative)
to the existing amount flowers in node
u
. It is guaranteed that after this operation, flowers in a node will be non-negative and sum of flowers of all node of the tree will be at most 10
18
.
Note that 1 is the root of the tree.
Input
The first line of the input contains two integers
n
(2 ≤ n ≤ 10
5
) and
q
(1 ≤ q ≤ 10
5
) where n is the number of vertices of the tree and q is the number of queries you have to perform.
Each of the next n-1 lines contains two integers
a
(1 ≤ a ≤ n) and
b
(1 ≤ b ≤ n) which denote an edge between a and b. The next line contains n non-negative integers c[1], c[2] ... c[n] (0 ≤ c[i] ≤ 10
13
) where c[i] denotes the number of flowers in i’th node. Next q lines contain queries of the format described above.
Output
For each query of the first type print minimum number of nodes you have to visit to collect at least
x
(1 ≤ x ≤ 10
18
) flowers. If it's impossible to collect at least
x
flowers visiting all the vertices from
v
to
u
then print
-1
.
Example
Input:
6 5
1 2
1 3
2 4
2 5
5 6
2 3 13 5 7 11
1 1 6 10
1 1 6 12
1 1 6 19
2 5 5
1 1 6 23
Output:
1
2
3
2 | 34,581 |
See you again? (DST)
Tareq and Shawon were two friends of the problem setter's. Many years ago, they died in a road accident. The problem setter still misses them. He gives you the following task in memory of his friends.
You're given a tree with n nodes and n-1 edges. Each node contains a single character.
(A node can contain any of the lowercase Latin letters 'a' to 'z' or special symbol '&')
. You've to answer if it is possible to find the string "
tareq&shawon
", without quotes, as a subsequence if you choose a path from the root node to a leaf node. If it is possible then print the path that contains the mentioned string as a subsequence. If there are multiple paths containing the above string as a subsequence, print the lexicographically smallest one.
Note that 1 is the root of the tree and you've to print the whole path from the root node to a leaf node that contains the above string as a subsequence.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 1000) - the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 10
5
) - number of nodes in the tree.
The next n-1 lines contains two integers u (1 ≤ u ≤ n) and v (1 ≤ v ≤ n) denotes an edge between node u and v.
The next line contains n space separated characters where c[i] corresponds to the character in the i’th node. c[i] can be a lowercase Latin letter or special symbol '&'.
It is guaranteed that the sum of n over all test cases does not exceed 10
5
.
Output
For each case print the case number and then print "YES" if there is a path from the root node to a leaf node that contains the mentioned string as a subsequence. And print the lexicographically smallest path that contains the mentioned string as a subsequence.
Otherwise, print "NO".
Example
Input:
1
31
1 2
2 3
3 8
8 9
9 13
13 17
17 18
18 23
2 4
4 7
7 10
10 14
14 16
16 19
19 22
22 28
28 29
29 30
30 31
2 5
5 6
6 11
11 12
12 15
15 20
20 21
21 24
24 25
25 26
26 27
t a r r r e e e q q q & & & s s s h h h a a a w o n m w o n x
Output:
Case 1: YES
1 2 4 7 10 14 16 19 22 28 29 30 31
Notes
There are two possible path from the root to a leaf that contains mentioned string as a subsequence. They are 1 2 4 7 10 14 16 19 22 28 29 30 31 and 1 2 5 6 11 12 15 20 21 24 25 26 27. The first one is lexicographically smaller. | 34,582 |
Square Pentagon (SQPENT)
Garima is a Geometry enthusiast, she loves solving geometry puzzles and creating new puzzles by herself. One fine day she was trying to arrange some "dots" (.) in a form of square.
As shown in figure below:
She observes that the number of dots needed to create a square of size 'n' is
n × n
i.e. 1, 4, 9, 16, 25, and so on.
She wanted to make larger polygons with these dots, so she started making pentagons, as shown in figure below.
Being a bright Mathematics student, she is quick to figure out that to create pentagon of size 'n' she needs
(3 × n × n - n) / 2
dots i.e. 1, 5, 12, 22, 35, and so on.
Now she wonders, if she can ever use the same number of dots to make a square as well as a pentagon, of different sizes of course.
She tries a few numbers, but cannot think of any number other than 1, which can make both square and pentagon.
She tried a lot of numbers, now she thinks, such numbers might be too big, so she asks her programmer friend to write a program to find such numbers which can arranged as both square and pentagon.
Her programmer friend, understanding that these numbers can be big, promises her to find such numbers modulo 3367900313, a random big enough prime number.
Assume that you are her friend, now help her to find these numbers!
Input
The first line contains a single positive integer 't', describing the number of test cases.
Next 't' lines contains positive integer 'r', such that 1 ≤ r ≤ 2500. Also, 1 ≤ t ≤ 100.
Output
For each test case, find out r
th
number, when considered in sorted ascending order, which can be arranged as a pentagon as well as a square, as described in the problem
Print a single line corresponding to each test case. Since the answers can be long, so don't forget to take modulo 3367900313
Example
Input:
2
1
2
Output:
1
9801
Explanation
The first such number is 1, after that next number is 9801 which can make a square of size 99, as 99 × 99 = 9801 and it can make a pentagon of size 81, as (3 × 81 × 81 - 81) / 2 = 9801. | 34,583 |
Comet Number (CPDUEL5A)
A positive integer
X
is a comet number if there exists 5 positive integers
A B C D E
such that:
A + B + C + D = X
A + E, B - E, C * E,
and
D / E
are pairwise equal, meaning
A + E = B - E = C * E = D / E
Kanata gave Suisei
N
positive integers
A
i
for
1 ≤ i ≤ N
.
Suisei would like to know whether A
i
is a comet number or not.
Input
The first line contains an integer
N
.
The next
N
lines contain an integer A
i
.
Output
Print
N
lines.
The
i
-th line contains the string "YES" (without quotes) if A
i
is a comet number and "NO" (without quotes) otherwise.
Example
Input:
4
8
1
69
128
Output:
YES
NO
NO
YES
Explanation
8 is a comet number as there exists a valid quintuple
(A, B, C, D, E) = (1, 3, 2, 2, 1)
.
128 is a comet number as there exists a valid quintuple
(A, B, C, D, E) = (31, 33, 32, 32, 1)
.
Constraints
1 ≤ N, A
i
≤ 10
5 | 34,584 |
Asacoco Prescription (CPDUEL5B)
Watame needs to consume asacoco. However, consuming too much asacoco can be dangerous, so she consults with a doctor.
The doctor recommends her a limit for every day. Let
A
i
be
a real number
denoting the limit of asacoco allowed to be consumed in the
i
-th day.
Uniquely, the array
A
i
is a non-decreasing arithmetic sequence.
An element
A
i
can be represented as A
0
+ i * d where d is a constant real number. It is guaranteed that A
0
is an integer
.
After receiving the doctor's prescription, Watame went home only to realise the receipt has a different array from the recommendation given from the doctor.
What was printed on the receipt was an array of integers
S
i
with a note that
S
i
= [A
i
].
Here,
[x]
denotes the largest integer less than or equal to
x
(floor function).
For rehabilitation, Watame is forced to minimize
d
(since minimizing
d
minimizes
A
i
too, thus less asacoco for Watame) such that the information printed on the receipt is still valid.
If there exists a valid
d
, it can be represented as a fraction
P / Q
where
GCD(P, Q) = 1
. Print the answer in the form of
P * Q
-1
modulo
10
9
+ 7
.
There can be cases where the receipt can be faulty (the cashier and the doctor may as well be drunk of asacoco) and there is no valid
d
. In this case, print
-1
instead.
Input
The first line contains an integer
N
, the size of the array
S
.
The next lines contains
N
integers
S
i
.
Output
Print an integer representing the answer in the form of
P * Q
-1
modulo
10
9
+ 7
.
If there does not exist a valid
d
(the receipt may be faulty), print -1 instead.
Example
Input 1:
6
1 2 3 4 5 6
Output 1:
1
Input 2:
5
3 3 3 3 4
Output 2:
250000002
Input 3:
2
4 1
Output 3:
-1
Explanation
The answers for sample 1 and 2 in decimal format is 1.0 and 0.25 respectively.
Constraints
1 ≤ N ≤ 10
5
1 ≤ S
i
≤ 10
9 | 34,585 |
Phasmophobia (CPDUEL5C)
Okayu and Korone are playing Phasmophobia.
There are
N
rooms, numbered
1
to
N
. Each player has to enter the
N
rooms in an order.
Let
P
be the permutation of size
N
representing the order of rooms Okayu enters, and
Q
for Korone.
Korone doesn't want to be too far from Okayu, so they set up a plan as the following:
Okayu will enter the rooms in numerical order. Formally,
P = {1, 2, 3, ... N}
.
Korone will enter the rooms in a way such that
|P
i
- Q
i
| ≤ K
for every
1 ≤ i ≤ N
.
How many configurations can Korone enter the rooms? Since the answer can be large, print the answer modulo
10
9
+ 7
.
Input
The first and only line contains two integers
N
and
K
.
Output
Print an integer denoting the number of permutations
Q
satisfying the conditions above in modulo
10
9
+ 7
.
Samples
Input 1:
3 1
Output 1:
3
Input 2:
3 2
Output 2:
6
Explanation
In sample 1, the possible configurations are
{1, 2, 3}
,
{2, 1, 3}
, and
{1, 3, 2}
.
In sample 2, all permutations are valid.
Constraints
1 ≤ N ≤ 1000
1 ≤ K ≤ 5 | 34,586 |
Unique Sequence (FLT)
Given a series defined by:
F(n)=(F(n-1)+F(n-1)+F(n-1) ... +pth time)%1000000007 (10^9+7).
where p is any prime number between (1-100). Now you are provided n and nth term of the sequence. Find the first term of the given series.
Input
Input contains only three integers n, nth term and p separated by spaces.
Here n will be between 1 to 1000000000 inclusive.
and each term ranges between 0 to 1000000006 inclusive.
Output
Output a single integer that is first term of the sequence.
Example
Input:
5 32 2
Output:
2 | 34,587 |
Brenden Politeness Filter (BPF1)
Brenden is a good guy, he wants to make a filter to be put in class rooms, so then no one whould be able to throw bad words to others.
He invented a politeness filter, which could be attached to the ceil of the class room, and it will allow only good words to pass.
How the filter works?
The politeness filter contains several steps of filtering (layers), each step (layer) would test the word against its own filtering settings, then send the word into its queue if the word matched its filtering string, the queue will forward those words to specific group of people.
In another way, the configuration consist of several consecutive QUEUE tags, each one has a name, BPF properties:
<QUEUE name="queue_name"
bpf = "bpf_string"
/>
As you know, talking is not like shouting, so the filter will distinguish between normal words, and shouted words.
The BPF string is written in the following grammar:
<bpf_string> ::= "" | <words_filter> "|| (shout and " <words_filter> ")"
<words_filter> ::= "(" <many_words_filter> ")"
<many_words_filter> ::= <single_word_filter> | <single_word_filter> " or " <single_word_filter>
<single_word_filter> ::= "word " <word>
(Please review the
Backus–Naur form
if you didn't understand the notation.) If the notation is a little bit hard, don't worry, the example is clear.)
Ok, Your task now is to write the configuration of a politeness filter!
The input will start with the word "Config:" then following 4 lines with the following grammar:
<line> ::= " - " <queue_name> "=" <words_specifications>
<words_specifications> ::= "" | <words_list>
<words_list> ::= <word> | <word> "," <words_list>
Please note that <queue_name> and <word> are strings that consists of combinations of lower case, upper case, numbers, underscores only (no other punctuations, no spaces), with a limit of 50 character each, and the <word_list> contains no more than 10 words.
Also, you can assume that queue names are different, also the <word_specifications> are different.
Final note, if the <word_specifications> is empty, don't print the queue at all.
And after printing all the queues, please print a final queue with queue_name="OTHER" and an empty BPF.
Ok, that's all, here is some examples:
Examples
Input:
Config:
- BPF_WORDS_GOOD=Palastine,Syria
- BPF_WORDS_SECRET=
- BPF_WORDS_BAD=Materialism,Racism
- BPF_WORDS_POLITICAL=tyranny
Output:
<QUEUE name="BPF_WORDS_GOOD"
bpf = "(word Palastine or word Syria) || (shout and (word Palastine or word Syria))"
/>
<QUEUE name="BPF_WORDS_BAD"
bpf = "(word Materialism or word Racism) || (shout and (word Materialism or word Racism))"
/>
<QUEUE name="BPF_WORDS_POLITICAL"
bpf = "(word tyranny) || (shout and (word tyranny))"
/>
<QUEUE name="OTHER"
bpf = ""
/>
Input:
Config:
- BPF_WORDS_1=1111,2222
- BPF_WORDS_2=3333,4444,4455,4466
- BPF_WORDS_3=5555
- BPF_WORDS_4=7777,8888
Output:
<QUEUE name="BPF_WORDS_1"
bpf = "(word 1111 or word 2222) || (shout and (word 1111 or word 2222))"
/>
<QUEUE name="BPF_WORDS_2"
bpf = "(word 3333 or word 4444 or word 4455 or word 4466) || (shout and (word 3333 or word 4444 or word 4455 or word 4466))"
/>
<QUEUE name="BPF_WORDS_3"
bpf = "(word 5555) || (shout and (word 5555))"
/>
<QUEUE name="BPF_WORDS_4"
bpf = "(word 7777 or word 8888) || (shout and (word 7777 or word 8888))"
/>
<QUEUE name="OTHER"
bpf = ""
/> | 34,588 |
TABTABTAB (TABY)
Have you ever used a text editor like notepad ++ or sublime? In the text editor software, several lines can be selected at once so that in 1x the tab key on the keyboard is pressed, all lines will move forward. Or press Shift Tab 1x then all the selected lines will be backward together. Selection of rows must be carried out sequentially (for example selecting rows 1 to line 5) and should not select lines that are jumped (not consecutive).
Input
Input begins with a T representing a testcase (1 <= T <= 100) and is followed by N (amount of text, 1<=N<=100000) inside the text editor. Each text in the text editor has an initial tab position. The line after N is the starting tab position of each text. Two Lines after N is the tab position the goal is to reach.
Output
Each time the Tab key or Shift Tab key is pressed will count as one press of the key. Find the minimum number of Tab or Shift Tab presses to reach the destination.
Example
Input:
1
3
1 2 3
3 4 5
Output:
2 | 34,589 |
Selling Greeting Cards (SLNCRD)
You are familiar with greeting cards, right?
On the occasion of EID, Mahir along with his cousins, decided to sell special greeting cards for wishing EID. As per decision, they set up their small stall. And they started selling. Initially they have
N
Eid cards. There is a serial number of each EID card. The serial number of 1
st
Card is 1, 2
nd
card is 2 and so on. The serial numbers of the EID Cards are written on it.
Mahir came up with a great pricing idea. As they are looking to make much profit, the price of the EID cards are not fixed. They will fix according to their idea. So let’s describe it.
Firstly, they will consider two things, the serial number of the card they are selling and the number of cards left before selling current card. And the price of this card will be product of this two.
Let’s make it straight forward:
Consider, they are selling
i
th
card. So the serial number is
i.
And so there will be actually
n-i+1
cards left before selling this card.
So the price of the card will be
i * (n-i+1).
It is guaranteed that they will sell all the cards. Your task is to calculate the total income after selling all the cards.
Input
The first line of the input contains an integer
T
(
1 ≤ T ≤
1,000)
. Each of the following
T
lines will have an integer
N (
1 ≤ N ≤
1,000,000,000)
.
Output
For each case, output a single line consisting of the total income of Mahir modulo
1,000,000,007
.
Example
Input:
2
5
10
Output:
35
220 | 34,590 |
Precious Prizes (PRIZES)
As the winner of the competition, you are asked to take prizes that are numbered from 1 to K. Each i-prize weighs Wi kg and is worth Hi dollar. You are carrying a bag with a capacity of N kg. The prizes must be put in this bag to be taken home. Each prize must be taken in its entirety and may not be taken in parts. Determine which prizes need to be taken, so that the total value of the prizes can be a high as possible. You may carry a number of prizes, so that the total weight is still ≤ N kg.
Input
The first line contains the number of test cases T (1 ≤ T ≤ 100).,The next line contains two integers separated by spaces, namely N and K.
The next K line contains two Wi and Hi numbers, which represent a description of a prize.
Output
Print the serial number of the prizes so that the total value is maximum. Print these numbers in order from small to large.
If there is more than one optimal prize picking method, print out a method for picking prizes that minimizes weight.
If there is more than one method, prioritize the prizes with the smaller number.
Constraints
1 ≤ N ≤ 2,000
1 ≤ K ≤ 100
1 ≤ Wi, Hi ≤ 2,000, for 1 ≤ i ≤ K
Example
Input:
2
5 3
9 3
10 2
32 2
11 3
10 30
6 17
5 14
Output:
Case 1:
0
Case 2:
2
3 | 34,591 |
Robot World (ROBOWORLD)
Garima is a student of Artificial Intelligence, she is specializing in robotics. She is designing various simulations to test run her robot algorithms. The robot works in a 1-dimensional world (which has a starting point known as origin). If a robot is 5 units away from origin, then robot is said to be at the ordinate 5. Similarly if robot is 2.5 unit away from origin, then robot is said to be at the ordinate 2.5. Robots usually operate in groups. A group of robots can be described in terms of their individual ordinates. For example, if there are three robots in a group which are present at 1.3 units, 0 units and 5 units respectively away from origin, then we can say that the robot group is the ordered tuple <1.3, 0, 5>.
One of the attributes of the robot is its power. Given a robot's ordinate we can determine the power of a robot using a given linear function called robot power function. Even though linear functions are of the form ax + b, but robot power functions are of the form ax and don't have any constant term. Robot's in the same group have same robot power function. For example, if robot power function is given by function f(x) = 2x, then robots in the group <1.3, 0, 5> have powers 2.6 units, 0 units and 10 units respectively. The average power of the group is given by (2.6 + 0 + 10)/3 = 4.2.
Given two robot groups (containing same number of robots), Garima wants to find robot power functions f(x) and g(x) such that f(x) = ax and g(x) = bx and 'a' and 'b' are positive integers and absolute difference between the average power of the two robot groups is minimized. Since 'a' and 'b' needs to be small, so a
2
+ b
2
should also be minimized.
More mathematically, given the robot groups <x
1
, x
2
... x
n
> and <y
1
, y
2
... y
n
>, find positive integers 'a' and 'b' such that |(1/n) * ∑ (a*x
i
- b*y
i
)| is minimized. Since, there is a possibility that there are multiple such 'a' and 'b' so Garima puts yet another constraint of minimizing a
2
+ b
2
Input
The first line tells the number of test cases 't'.
Each test case begins with a number 'n'. 'n' corresponds to the number of robots in robot groups.
The next 'n' lines of the test case consist of two space separate real numbers. For example the i
th
line contains real numbers 'x
i
' and 'y
i
' which represent the ordinates of one robot from each of the two robot groups.
These 'n' lines describe the two robot groups <x
1
, x
2
... x
n
> and <y
1
, y
2
... y
n
>. It is also given that not all robots in any robot group are 0 units away from origin.
1 ≤ t ≤ 100
1 ≤ n ≤ 1000
0 < ∑x
i
≤ 10
14
0 < ∑y
i
≤ 10
14
x
i
and y
i
can have
at most 4 digits after decimal
.
Not all of x
i
are zero and not all of y
i
are zero.
All x
i
≥ 0 and all y
i
≥ 0
#Note: x
i
and y
i
are
real numbers
and
NOT necessarily floating-point numbers
You can read more about floating-point numbers here:
https://en.wikipedia.org/wiki/Double-precision_floating-point_format
Output
Single line per test case.
Each line is of the form:
f(x) = ax, g(x) = bx
where 'a' and 'b' are the respective positive integers satisfying all the constraints given in the problem.
#Note: The uniqueness of 'a' and 'b' is mathematically guaranteed.
Example
Input:
3
4
7.4 0.0027
0.022 72
0.002 0.000
0.0 0
4
8.6 0.004
0.006 0.092
0.5 0
0.002 0.004
4
25 0.73
0.0062 1.4
1 0.012
0.07 0.0000
Output:
f(x) = 720027x, g(x) = 74240x
f(x) = 25x, g(x) = 2277x
f(x) = 10710x, g(x) = 130381x
Explanation
For the first test case, we can observe that |(720027 * 7.4 - 74240 * 0.0027) + (720027 * 0.022 - 74240 * 72) + (720027 * 0.002 - 74240 * 0.000) + (720027 * 0.0 - 74240 * 0)| = 0.
Since minimum absolute value can be zero so 720027 and 74240 satisfies the minimization constraint. Also, 720027 and 74240 are the smallest such values, hence they satisfy the minimization of a
2
+b
2
constraint too. | 34,592 |
Just Primes (JPM)
This problem is really simple, or is it? Given a positive integer
N
, calculate the
minimum
number of
distinct
primes needed such that their sum equals to
N
. A prime number is a natural number greater than
1
that cannot be formed by multiplying two smaller natural numbers. The first few prime numbers are
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
and so on.
Input
The first line contains an integer
T
, denoting the number of test cases. Each of the next subsequent
T
lines contain a positive integer
N
.
Constraints
1 ≤ T ≤ 50,000
1 ≤ N ≤ 50,000
Output
For each test case, first print the case number followed by the minimum number of distinct primes such that their sum equals to
N
. If
N
cannot be represented by a summation of distinct primes, then print the case number followed by
-1
. Refer to the sample input/output for more clarity of the format.
Sample Input
10
1
2
3
10
27
100
1000
4572
4991
49999
Sample Output
Case 1: -1
Case 2: 1
Case 3: 1
Case 4: 2
Case 5: 3
Case 6: 2
Case 7: 2
Case 8: 2
Case 9: 3
Case 10: 1
Challenge
Too easy? Try the harder version here -
Just Primes II | 34,593 |
Just Primes II (JPM2)
Given a positive integer
N
, calculate the minimum number of distinct primes required such that their sum equals to
N
. Also calculate the number of different ways to select these primes. Two ways are considered to be different
iff
there exists at least one prime in one set not existing in the other.
Input
The first line contains an integer
T
, denoting the number of test cases. Each of the next subsequent
T
lines contain a positive integer
N
.
Constraints
1 ≤ T ≤ 500,000
1 ≤ N ≤ 500,000
Output
For each test case, output two integers
X
and
Y
separated by a single space.
X
denotes the minimum number of distinct primes required such that their summation equals to
N
, and
Y
is the number of ways to select these primes. If it is not possible to express
N
as a summation of distinct primes, set
X
and
Y
to
-1
and output them. You can safely assume that the answer will always fit in a signed 32 bit integer.
Sample Input
20
1
2
10
27
100
666
1000
1729
4572
4991
10000
100000
480480
482790
499799
499847
499901
499979
499999
500000
Sample Output
-1 -1
1 1
2 1
3 3
2 6
2 31
2 28
3 2393
2 110
3 13396
2 127
2 810
2 8499
2 8291
3 31121027
3 31139901
3 31124665
1 1
3 30974053
2 3052
Warm Up
Too hard? Try the easier version here -
Just Primes | 34,594 |
Distinct Cyclings (CYCLINGS)
The Kingdom of Gridland contains
P
provinces. Each province is defined as a
2 × N
grid where each cell in the grid represents a city. Every cell in the grid contains a single lowercase character denoting the first character of the city name corresponding to that cell.
From a city with the coordinates
(i, j)
, it is possible to move to any of the following cells in unit of time, provided that the destination cell is inside the grid:
(i + 1, j)
(i, j + 1)
(i - 1, j)
(i, j - 1)
A knight wants to visit all the cities in Gridland. He can start his journey in any city and immediately stops his journey after having visited each city at least once. Moreover, he always plans his journey in such a way that the total time required to complete it is minimum.
After completing his tour of each province, the knight forms a string by concatenating the characters of all the cells in his path. How many distinct strings can he form in each province?
Input
The first line contains a single integer
P
, denoting the number of provinces. The
3 × P
subsequent lines describe each province. The first line contains an integer
N
, denoting the number of columns in the province. Each of the next two lines contains a string
S
, of length
N
and consisting of only lowercase letters denoting the characters for the first and second row of the province.
Constraints
1 ≤ P ≤ 15
1 ≤ N ≤ 600
Output
For each province, print the number of distinct strings the knight can form on a new line.
Sample Input
3
1
a
a
3
dab
abd
5
ababa
babab
Sample Output
1
8
2
Explanation
For the second province, here are all possible unique strings that can be formed:
abdbad, adabdb, badabd, bdbada, dababd, dabdba, dbabad, and dbadab
.
Reference
HackerRank - Gridland Provinces | 34,595 |
Battle Of The Bastards - Kings Vs Rooks (BATTLECRY)
Chess
is a two-player strategy board game played on a
8 x 8
board. Each player begins with
16
pieces where each type of piece moves differently. Player 1 has all the white pieces and player 2 all the black ones, with white being the one to move first and then players take turns alternatingly until the game ends. The game is played on a square board of eight rows and eight columns. The rows are called ranks and are numbered 1 to 8 from bottom to top from white’s perspective. Similarly, the columns are called files and are denoted from
a
to
h
from left to right according to white’s perspective. The objective of the game is to threaten the opponent’s king in such a way that escape is not possible, i.e, checkmate the opponent. If a player’s king is threatened, it is said to be in check and the player must remove the king from check on the next move by either moving to a safe square or capturing or blocking the attacking piece(s). The figure shows the starting position for the game of chess.
In this problem, we’ll be considering a slightly modified version of chess with the following rules:
The game will be played on a
N x N
board.
The game will consist of exactly 4 pieces - The white king, the black king, and two white rooks. All four pieces must be placed on different squares of the board.
Kings can move to any adjacent square (horizontally, vertically, or diagonally), unless the square is outside the board or occupied by a friendly piece or if the move would place the king under check.
Rooks can move to any square in the same rank or file, but not by jumping over other pieces. Also, it cannot land on a square occupied by a friendly piece.
A piece
X
is threatened by another enemy piece
Y
, iff
Y
can reach
X
in exactly one legal move.
A piece
X
can capture another enemy piece
Y
iff
X
can reach
Y
in exactly one legal move. On capturing, piece
Y
is removed from the board and
X
takes its place. Note that if
X
is the king, then it cannot capture
Y
if
Y
is guarded by an enemy piece. That is the king can never move and put itself in danger where it is attacked by an enemy piece.
The two kings cannot ever be in adjacent (horizontally, vertically or diagonally) squares.
The objective of the game is to place the four pieces on unique squares of the board in such a way that if it is black’s move, then the black king is attacked and has no legal moves. That is, the black king must be threatened by at least one of the white rooks and has no way to move to a safe square or eliminate the checks (by capturing the attacking pieces if not guarded). Note that it is not necessary for the board configuration to be legal following the exact rules of chess. That is, if
N = 8
there might be valid configurations in our modified game that might never appear in a game of chess. Like the figure shown below, which can never occur in a proper game of chess given that it is black’s turn to move, although it would be a perfectly valid configuration in our game.
Given
N
, you need to count how many ways you can place one white king, one black king, and two white rooks in the chessboard such that the black king is threatened and has no way to escape the threat given it is black’s turn to move. Two configurations are different if either any of the squares contain different pieces or one square contains a piece but the other does not. Note that every square is uniquely represented by its rank and file and hence mirrored or reversed configurations of the same configuration will be considered as different configurations. Also note that the white king, black king, and white rooks are distinguishable but the two white rooks are identical. So in the figure above, if we swap the two rooks, the new configuration will be the same as the old one.
Since the number of ways can be huge, you need to output it modulo
7340033
.
Input
The first line contains the number of test cases denoted by
T
. The next
T
lines contain the board dimension
N
.
Constraints
1 ≤ T ≤ 20
1 ≤ N ≤ 10
5
Output
For each case, output one line. First output the case number then the number of valid ways modulo
7340033
. Please refer to the sample i/o for more clarity on the format.
Sample Input
8
1
2
3
4
5
6
7
8
Sample Output
Case 1: 0
Case 2: 0
Case 3: 232
Case 4: 1432
Case 5: 5188
Case 6: 14536
Case 7: 34464
Case 8: 72392
Explanation
For a
8 x 8
board, here are some valid configurations:
For all of these boards, the black king is attacked and has nowhere to go. Also, both the white rooks are placed on the board and the kings are not in adjacent positions.
And here are some invalid ones:
For the first board, the black king can move and capture the attacking white rook thereby removing the check and moving to a safe square.
For the second board, although the black king is attacked and cannot capture anything because all the pieces are guarded, the two kings are adjacent which is not allowed. Hence it is not a valid checkmate position.
For the third board, it is a stalemate. That is the black king has nowhere to go but it is also not attacked. So no checkmate.
For the fourth board, it is checkmate and the black king has nowhere to go. But we haven’t placed both the rooks on the board and hence this is not a valid position. | 34,596 |
Arithmetic Progression Query (UPDTARR)
You have an array of size
N
initially filled with 0. You have
Q
queries. In each query, you will be given two integers
a
and
b
. For each query, you need to add
1
at the following valid indices: ... ... a - 2 * b, a - b, a, a + b, a + 2 * b ... ... The indices that lie in the range
[1, N]
are only considered valid. Print the final array after the last update.
Input
The first line contains the number of test cases. Then T test cases follow. Every test case starts with two integers N and Q. After that, Q lines follow. In each line there will be two integers describing that query.
1 ≤ T ≤ 10
1 ≤ N, Q, a, b ≤ 100000
Output
Print the final array after the last query with the case number.
Example
Input:
1
5 1
1 2
Output:
Case 1: 1 0 1 0 1 | 34,597 |
Mines of Moria (MORIA)
In the Mines of Moria, the job of Gakrobera Silverborn the dwarf is to load minecarts with
N
stones. The stones are numbered, from 1 to
N
, and a given minecart can only be loaded with consecutive stones.
Each stone has a weight between 1 kg and 1000 kg, which we assume to be an integer. The optimal load of a mine cart is 2000 kg. The score of a minecart loaded with
W
kg of stones is
(
W
− 2000)
2
. After all stones have been loaded in minecarts, the total score is the sum of the score of each minecart. The lower the total score is, the better it is.
To help Gakrobera, find the best possible way to load minecarts, given the weights of each stone from 1 to
N
.
For example, given four stones of 700 kg, Gakrobera will prefer to load them all in a single minecart (total score
800
2
= 640 000
). But given four stones of 800 kg, Gakrobera will prefer to load two minecarts with two stones (total score
400
2
+ 400
2
= 320 000
).
Input
The input begins with an integer
T
(
1 ≤
T
≤ 1000
), the number of test cases. Then
T
test cases follow.
Each test case is a line of space-separated integers. The first integer
N
(
1 ≤
N
≤ 10
6
) is the number of stones to be loaded. Next come
N
integers
w
1
, …,
w
N
(
1 ≤
w
i
≤ 1000
), where
w
i
is the weight of the stone
i
.
Output
For each test case, output the smallest possible total score.
Example
input
3
4 700 700 700 700
4 800 800 800 800
10 100 200 300 400 500 600 700 800 900 1000
output
640000
320000
270000 | 34,598 |
The triangle of Pascal modulo 2 (TRIMOD2)
Consider Pascal’s triangle modulo 2. The first nine rows are given below:
1
1 1
1 0 1
1 1 1 1
1 0 0 0 1
1 1 0 0 1 1
1 0 1 0 1 0 1
1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 1
Let
F
(
n
)
be the number of
1
in the first
n
rows. So that
F
(0) = 0
,
F
(1) = 1
,
F
(2) = 3
, etc.
Given
a
, find the smallest integer
n
such that
F
(
n
) ≥
a
. Let
N
(
a
)
denote this integer.
Input
A list of integers
a
1
, ...,
a
l
, between
0
and
10
18
, one per line.
Output
The integers
N
(
a
1
), ...,
N
(
a
l
)
, one per line.
Example
input:
0
1
4
15
output:
0
1
3
6 | 34,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.