task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Jumping Beans (ACPC10H)
N jumping beans are standing in a line. At each second, a bean jumps. Your assignment is to figure the final position of the beans after a given number of seconds. To make the explanation easier, let’s assign a unique letter to each bean, and for simplicity, let’s assume the beans are initially standing in order: A, B, C, etc. To simplify even further, let’s assume N = 4, so initially the beans are standing in the order ABCD. At the first second, A jumps, swapping its place with B. Now the order is BACD. At the second second, it’s B’s turn, but this time swapping its place with A, then C, resulting in the standing order ACBD. More formally: at second s, the left most bean that has jumped the least number of times will do the swap s times, each time swapping its place with the bean on its right. Note that when the right-most bean swaps, it moves to the left-most position, pushing everybody else one place to the right. So, continuing with the previous example, and starting with the arrangement ACBD, it is bean C’s turn, since it is the left-most bean that has jumped the least amount of times. Being at the third second, C will swap three times, first resulting in ABCD, then ABDC, and then CABD. At the fourth second, it’s bean D’s turn to jump. At the fifth second, and since all the four beans have jumped exactly once, the bean that will jump is the bean standing at the left-most position.
Input
Your program will be tested on one or more test cases. Each test case is specified on a single line specifying an integer T and a string S where (0 < T < 10
9
) is the number of seconds and S is the initial arrangement of the beans. S is a non empty string made of different upper-case letters (’A’. . . ’Z’).
The last test case is followed by a line having a single 0.
Output
For each test case, print the following line:
k. S
Where k is the test case number (starting at one,) and S is the arrangement of the beans after jumping for T seconds.
Example
Input:
3 ABCD
13 ACM
0
Output:
1. CABD
2. CAM | 32,200 |
The Cyber Traveling Salesman (ACPC10I)
In light of the exploding population on earth, a number of cities are being constructed on the moon. We would like you to assist in determining the best road system for these cities. Considering the high cost associated with building roads on the moon, all what is required is for the roads to form a cycle starting from the city that appears first in the input, passing through all other cities exactly once (but in any arbitrary order,) and then ending back to the first. (Yes, this problem is a variation of the traveling-salesman problem.)
You are given the cost of building a road between each pair of cities. Roads are one-way, but the cost for building a road from city i to j is the same as the cost of building from city j to i. When roads intersect at a location that is not a city, you must account for the cost of constructing bypassing bridges. Constructing a bypass system costs k ∗ (k − 1) ∗ C/2 where k is the number of roads intersecting at that location, and C is a given constant. Note that the cities are laid out so that no three cities fall on the same straight line.
Input
Your program will be tested on one or more test cases. Each test case is specified using 2 ∗ N + 1 lines. The first line specifies two integers: (2 < N < 9) is the number of cities and (0 < C ≤ 1, 000, 000) is the coefficient used in determining the cost of building bridges. Following the first line, the Cartesian coordinates of the cities are specified in order. Each city is specified on a separate line made of two integers: xi and yi where (−1, 000 ≤ xi , yi ≤ 1, 000). No two cities are located at the same (x, y) location.
The last N lines of a test case specify an N ∗ N matrix representing the cost of building a road between any two cities. The matrix is specified using N lines, each with N integers in a row-major format. The j th value on the ith row, denoted as cij is the cost of building a road from city-i to city-j where (0 < cij ≤ 10
6
) and (cij = cji ) and (cii = 0).
The last case is followed by a line having two zeros.
Output
For each test case, print the following line:
k. M
Where k is the test case number (starting at one,) and M is minimum cost needed to build the road system.
Example
Input:
4 1
1 2
0 1
2 1
1 0
0 1 8 3
1 0 3 9
8 3 0 2
3 9 2 0
4 100
1 2
0 1
2 1
1 0
0 1 8 3
1 0 3 9
8 3 0 2
3 9 2 0
0 0
Output:
1. 10
2. 20 | 32,201 |
World of cubes (ACPC10F)
You’ve been assigned the task of programming a new video game called the World of Cubes. The game is played inside a box-shaped object (mathematically speaking: a rectangular cuboid) which we’ll call the hall. Within the hall, the player is assigned N positions, called focal points.
The player must build N cubes, all parallel to the axes, and each is centered around one of the focal points. The mission is for the N cubes to completely fill the hall. It is acceptable for the cubes to overlap and even to extend beyond the hall. The only restriction is that all the cubes must be of equal side-length. And we would like you to compute the minimum such length.
Input
Your program will be tested on one or more test cases. Each test case is specified using N +1 lines.
The first line specifies four integers: (1 ≤ N ≤ 50) is the number of cubes and (1 ≤ X, Y, Z ≤ 10
9
) are the dimensions of the hall. One corner of the hall is at the origin (0, 0, 0), with the opposing corner at (X, Y, Z).
N lines follow, each specifying the coordinate of a focal point using three integers: (0 ≤ x ≤ X), (0 ≤ y ≤ Y), and (0 ≤ z ≤ Z).
The last test case is followed by a line containing four zeros.
Output
For each test case, print the following line:
k. D
Where k is the test case number (starting at one,) and D is an integer which is the smallest length of the cube edges so that the N cubes would completely fill the hall.
Example
Input:
2 4 4 8
2 2 2
2 2 6
2 4 4 8
2 2 2
2 2 5
0 0 0 0
Output:
1. 4
2. 6 | 32,202 |
Sometimes, a penalty is good! (ACPC10E)
FIFA is considering a few changes to the way it organizes the Football World Cup. Currently, 32 teams compete for the World Title in two stages. During the first stage, known as the groups stage, the 32 teams are split evenly into 8 groups. Every team in the group plays 3 games, one against each team in their own group. Teams are then ranked within their group according to some points system. During the second (and final) stage, the top two teams from each group advance to the knockout stage where eight games are played to determine eight winners who would then play four games to determine four winners, then two games to determine the two winners who would then play the final game to determine the world champion. Needless to say, for the knockout stage to work, the number of teams in that stage has to be a power of two. FIFA is considering adding more groups, adding more teams to groups, and possibly changing the number of teams advancing from each group to the knockout stage. In addition, FIFA is considering having certain teams (previous champion, host country, etc.) advance to the knockout stage directly (without having to play in the groups stage.) But FIFA needs to know how many games will be played if any of these changes are applied. Please help them!
Input
Your program will be tested on one or more test cases. Each test case is specified on a single line made of 4 natural numbers with the following format:
G T A D
Where (G > 0) is the number of groups; T is the number of teams in each group; A is the number of teams advancing from each group to the knockout stage; and D is the number of teams directly advancing to the knockout stage without going through the groups stage. Note that (0 < A ≤ T) and that the four numbers in the input are no larger than 2
16
.
If the total number of teams in the knockout stage is not a power of two, your program must increase them to the closest power of two.
The last test case is followed by a dummy line made of four -1’s.
Output
For each test case, print:
G*A/T+D=X+Y
where G, A, T, and D are as in the input, X is the total number of games, and Y is the number of teams your program determined it must add.
Example
Input:
8 4 2 0
8 4 2 1
-1 -1 -1 -1
Output:
8*2/4+0=63+0
8*2/4+1=79+15 | 32,203 |
What’s Next (ACPC10A)
According to Wikipedia, an arithmetic progression (AP) is a sequence of numbers such that the difference of any two successive members of the sequence is a constant. For instance, the sequence 3, 5, 7, 9, 11, 13 ... is an arithmetic progression with common difference 2. For this problem, we will limit ourselves to arithmetic progression whose common difference is a non-zero integer.
On the other hand, a geometric progression (GP) is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed non-zero number called the common ratio. For example, the sequence 2, 6, 18, 54 ... is a geometric progression with common ratio 3. For this problem, we will limit ourselves to geometric progression whose common ratio is a non-zero integer.
Given three successive members of a sequence, you need to determine the type of the progression and the next successive member.
Input
Your program will be tested on one or more test cases. Each case is specified on a single line with three integers (−10, 000 < a1, a2, a3 < 10, 000) where a1, a2, and a3 are distinct.
The last case is followed by a line with three zeros.
Output
For each test case, you program must print a single line of the form:
XX v
where XX is either AP or GP depending if the given progression is an Arithmetic or Geometric Progression. v is the next member of the given sequence. All input cases are guaranteed to be either an arithmetic or geometric progressions.
Example
Input:
4 7 10
2 6 18
0 0 0
Output:
AP 13
GP 54 | 32,204 |
Tri graphs (ACPC10D)
Here’s a simple graph problem: Find the shortest path from the top-middle vertex to the bottom-middle vertex in a given tri-graph. A tri-graph is an acyclic graph of (N ≥ 2) rows and exactly 3 columns. Unlike regular graphs, the costs in a tri-graph are associated with the vertices rather than the edges.
So, considering the example with N = 4, the cost of going straight down from the top to bottom along the middle vertices is 7 + 13 + 3 + 6 = 29. The layout of the directional edges in the graph are always the same as illustrated in the figure.
Input
Your program will be tested on one or more test cases.
Each test case is specified using N + 1 lines where the first line specifies a single integer (2 ≤ N ≤ 100, 000) denoting the number of rows in the graph. N lines follow, each specifying three integers representing the cost of the vertices on the ith row from left to right. The square of each cost value is less than 1,000,000.
The last case is followed by a line with a single zero.
Output
For each test case, print the following line:
k. n
Where k is the test case number (starting at one,) and n is the least cost to go from the top-middle vertex to the bottom-middle vertex.
Example
Input:
4
13 7 5
7 13 6
14 3 12
15 6 16
0
Output:
1. 22 | 32,205 |
Sum the Square (ACPC10B)
Take any positive number, find the sum of the squares of its digits, repeat! You’ll end up with an infinite sequence with an interesting property that we would like to investigate further. Starting with the number 5, the sequence is:
(5, 25, 29, 85, 89, 145, 42, 20, 4, 16, 37, 58 ...)
The interesting part is in what comes after 58: 5
2
+ 8
2
= 89 which is a number that’s already been seen in the sequence. In other words, after 58, the sequence will fall into the repeating cycle:
89, 145, 42, 20, 4, 16, 37, 58.
What’s amazing is that this cycle will appear for many other numbers: 3, 18, 36, and 64 just to name a few. (see figure below.) For some numbers, the sequence will fall into another repeating cycle by reaching 1. (see second figure below) For example, starting with 19, you’ll end up with the sequence:
(19, 82, 68, 100, 1...)
And that’s about it. Any number you choose will end up falling into a repeating cycle: Either the 89, 145... cycle or the 1... cycle.
Given two numbers, your objective is to generate as few numbers in their sequences for the two sequences to intersect at one common number. For example, given 61 and 29, we can achieve what’s required by generating the sequences: (61, 37, 58, 89) and (29, 85, 89). Similarly, for 19 and 100, the sequences would be (19, 82, 68, 100) and (100).
Input
Your program will be tested on one or more test cases. Each test case is specified on a single line having two integers (0 < A, B < 10
9
).
The last case is followed by a dummy line made of two zeros.
Output
For each test case, print the following line:
A B S
Where A, B are as in the input and S is the (minimum) sum of the lengths of the two sequences.
If the sequences starting at A and B do not intersect, then S = 0.
Example
Input:
89 89
19 100
61 19
0 0
Output:
89 89 2
19 100 5
61 19 0 | 32,206 |
Fibonacci Sum (FIBOSUM)
The Fibonacci sequence is defined by the following relation:
F(0) = 0
F(1) = 1
F(N) = F(N - 1) + F(N - 2), N ≥ 2
Your task is very simple. Given two non-negative integers N and M, you have to calculate the sum (F(N) + F(N + 1) + ... + F(M)) mod 1000000007.
Input
The first line contains an integer T (the number of test cases). Then, T lines follow. Each test case consists of a single line with two non-negative integers N and M.
Output
For each test case you have to output a single line containing the answer for the task.
Example
Input:
3
0 3
3 5
10 19
Output:
4
10
10857
Constraints
T ≤ 1000
0 ≤ N ≤ M ≤ 10
9 | 32,207 |
Horrible Queries (HORRIBLE)
World is getting more evil and it's getting tougher to get into the Evil League of Evil. Since the legendary Bad Horse has retired, now you have to correctly answer the evil questions of Dr. Horrible, who has a PhD in horribleness (but not in Computer Science). You are given an array of
N
elements, which are initially all 0. After that you will be given
C
commands. They are -
*
0 p q v
- you have to add
v
to all numbers in the range of
p
to
q
(inclusive), where
p
and
q
are two indexes of the array.
*
1 p q
- output a line containing a single integer which is the sum of all the array elements between
p
and
q
(inclusive)
Input
In the first line you'll be given
T
, number of test cases.
Each test case will start with
N
(
N
<= 100 000) and
C
(
C
<= 100 000). After that you'll be given
C
commands in the format as mentioned above. 1 <=
p
,
q
<=
N
and 1 <=
v
<= 10^7.
Output
Print the answers of the queries.
Example
Input:
1
8 6
0 2 4 26
0 4 8 80
0 4 5 20
1 8 8
0 5 7 14
1 4 8
Output:
80
508 | 32,208 |
Tree Topology (TTOP)
Given a rooted tree, a permutation of its nodes is valid if the following holds: for each pair of nodes
a
and
b
, if
a
is an ancestor of
b
, then
a
appears before
b
in the permutation. Let
P(t)
be the number of valid permutations for a tree
t
.
Given an integer N, you can construct all the possible trees of N nodes, numbered from 1 to N,
rooted at
1
. I'd like to know what's the sum of
P(t)
for all
t
that can be constructed for the given N.
We consider two trees equal iff each node in the second tree has the same parent as it does in the first one.
The picture shows all the possible trees for N = 3.
Input
A single integer N (1 ≤ N ≤ 1000000).
Output
A single integer representing the solution modulo 1000000007.
Example
Input:
3
Output:
4
Explanation:
If you take a look at the picture, you'll see that the first two trees have one valid permutation each, and the third tree has two, namely { 1, 2, 3 } and { 1, 3, 2 }. The total is, of course, 4. | 32,209 |
Possible Friends (SOCIALNE)
Josué, one of the undergraduate students in PUCMM, is developing a Social Network, but he is having difficulties in identifying the person that has more possible friends. Two persons are possible friends if they are not friends and they have at least one common friend, for example if person A is friend only to person B, and person B is friend of C, then, A and C are possible friends. You are about to help him in this task. Given the network table, you have to write a program that finds the person that has more possible friends, if more than one person matches this criteria, then select the one that comes first ( the one that has the lower ID).
Input
The first line is
T
(1 ≤
T
≤ 1,000), the number of test cases, then
T
test cases follow.
Each test case consists in a 'Y' or 'N' square matrix (
M
x
M
) representing the friendship of the network, where
M
is the number of persons.
Constraints
M
(1 ≤
M
≤ 50)
The square matrix has
M
lines, each line has
M
characters.
The first line of the matrix corresponds to person 0, the next line to person 1, and so on.
On each line the leftmost character corresponds to person 0, the next character to person 1, and so on.
So if character j of the line i is 'Y', it means that person 'i' is a friend of 'j'.
For each person i, character i of line i will be 'N'.
For each i,j character j of line i will be the same as character i of line j.
Output
For each test case, you have to output one line containing the ID of the person(0-based) that has more possible friends and the number of possible friends this person has, separated by a blank space.
Example
Input:
3
NYN
YNY
NYN
NYYY
YNNY
YNNN
YYNN
NNYNNNN
NNYNNNN
YYNYNNN
NNYNYNN
NNNYNYY
NNNNYNN
NNNNYNN
Output:
0 1
2 2
3 4 | 32,210 |
Fantastic Discovery (IMMERSED)
A fantastic discovery is about to happen in the biology field, and you are part of the team making the research. The research is about measuring the cells growth in an environment oxygen less and in presence of a toxic substance. The team came to a curious hypothesis, the analyzed data tells them that: the growth, the number of days and the toxicity; are related by this formula:
P
=
N*N
cN
where
P
is the growth measured in thousands of cells.
N
is the elapsed number of days.
and
c
is the constant that relates to the toxicity level of the experiment.
Your biology partners need to takeout some tissues from the cells when these cells reach a specific growth. They require you to write a program that tells them the exact time when this will happen, given a toxicity level and the growth required.
Input
The first line is
T
(1 ≤
T
≤ 40,000), the number of test cases, then
T
test cases follow.
Each test case is a line with 2 integers (
P c
) separated by a space.
P
(1 ≤
P
≤ 10
15
)
c
(1 ≤
c
≤ 5)
Output
For each test case you have to output the expected time in decimal format.
Example
Input:
3
1 1
3 4
100 1
Output:
1.000000
1.207384
3.086308
Note 1
: your output must contain at least 6 decimal places.
Note 2
: numerical problem. Output generated by submitted program should be exactly the same as test case with accuracy of 0.000001. | 32,211 |
Playground (AMR10A)
My kid's school cleared a large field on their property recently to convert it into a playing area. The field is polygonal. The school administration decided to separate the field into two areas by building a straight picket fence between the area for the older kids and the area for the younger kids. The fence would go between two non-adjacent vertices of the polygonal field, and given the shape of the field, all such possible fences would lie strictly and entirely within the field.
Naturally, the smaller of the two areas would go to the younger kids. So can you help the school determine what the area of the smaller play-area would be for different fence positions?
INPUT
The first line contains 2 numbers N denoting the number of points in the convex polygon and Q denoting the number of possible locations of straight line fences.
The next N lines contain 2 integers each. The ith line contains the integers xi yi denoting the coordinates of the ith point of the polygon. The points are given in clockwise order.
The next Q lines contain 2 integers a b denoting that a straight line fence is to be drawn connecting a and b.
OUTPUT
Output Q lines one corresponding to each query. For each query, output the area of the smaller region for the corresponding query truncated to 1 decimal place. Always have 1 digit after the decimal place, so if the answer is 1, output it as 1.0 instead.
CONSTRAINTS
4 <= N <= 50000
1 <= Q <= 50000
-20,000,000 <= x,y <= 20,000,000
0 <= a < b-1
b < N
SAMPLE INPUT
4 2
0 0
0 1
1 2
1 0
1 3
0 2
SAMPLE OUTPUT
0.5
0.5
EXPLANATION
The polygon is given by the points (0,0) (0,1) (1,2) (1,0).
In the first query, we join the points (0,1) and (1,0) which leads to the 2 areas given by (0,0) (0,1) (1,0) and (0,1) (1,2) (1,0). The first triangle has an area of 0.5 and the second triangle has an area of 1. The minimum of these 2 is 0.5.
In the second query, we join the points (0,0) and (1,2) which leads to the 2 areas given by (0,0) (0,1) (1,2) and (0,0) (1,2) (1,0). The first triangle has an area of 0.5 and the second triangle has an area of 1. The minimum of these 2 is 0.5. | 32,212 |
Regex Edit Distance (AMR10B)
A regular expression is used to describe a set of strings. For this problem the alphabet is limited to 'a' and 'b'. R is a regular expression if:
R is "a" or "b".
R is of the form "(R1R2)" where R1 and R2 are regular expressions.
R is of the form "(R1|R2)" where R1 and R2 are regular expressions.
R is of the form "(R1*)" where R1 is a regular expression.
The set of strings recognised by R are as follows:
If R is "a", then the set of strings recognised = {a}.
If R is "b", then the set of strings recognised = {b}.
if R is of the form "(R1R2)" then the set of strings recognised = all strings which can be obtained by a concatenation of strings s1 and s2 where s1 is recognised by R1 and s2 by R2.
if R is of the form "(R1|R2)" then the set of strings recognised = union of the set of strings recognised by R1 and R2.
If R is of the form "(R1*)" then the the strings recognised are the empty string and the concatenation of an arbitrary number of copies of any string recognised by R1.
The edit distance between two strings s1 and s2 is the minimum number of characters to be inserted/deleted or replaced in s1 to make it equal to s2.
Given two regular expressions R1 and R2, find the minimum edit distance amongst all pairs of strings s1 and s2 such that s1 is recognised by R1 and s2 is recognised by R2.
Input
The first line contains the number of test cases T. T test cases follow.
Each test case contains two lines containing two regular expressions R1 and R2. There is a blank line after each test case.
Output
Output T lines one corresponding to each test case containing the required answer for the corresponding test case.
Constraints
T ≤ 100
1 ≤ length(R1), length(R2) ≤ 50
You are guaranteed that R1 and R2 will conform to the definition provided above.
Input:
2
((a|b)*)
(a(b(aa)))
(a((ab)*))
(a(b(((ab)b)b)))
Output:
0
2
Explanation
For the first case R1 recognises all strings over the alphabet a and b. Thus it recognises the string "abaa" which is also recognised by R2.
For the second case the strings "aababab" and "ababbb" are recognised by R1 and R2 respectively and have edit distance of 2. | 32,213 |
Square Free Factorization (AMR10C)
You all know about factorization of an integer. Here we want you to factor a number into as few factors as possible. That is easy, you say, just have the number itself, and that will be the smallest number of factors i.e. 1.
But wait, I haven't finished — each of the factors that you find must be square-free. A square-free number, however you factor it, won't have any factor that is a perfect square. Of course, you can never include 1 as a factor.
Input
The first line of input is the number of test cases T. The next T lines each have an integer N.
Output
For each test case, output the smallest number of square-free factors.
Constraints
T ≤ 10
4
2 ≤ N ≤ 10
6
Example
Input:
2
6
8
Output:
1
3 | 32,214 |
Soccer Teams (AMR10D)
My kid's favorite subject is math, as you know by now. He is learning division now, and his teacher has taught him about even numbers being divisible by 2, numbers whose digits add up to a multiple of 3 being exactly divisible by 3 etc.
He was familiar with division by 11 during selection for soccer teams on his playground, and was wondering whether there was any easy rule to see if a number was divisible by 11. For example, he wondered, if he arranged a number of digits 0-9 in a row to form a number, which ones would be divisible by 11?
He decided to start off with d[1] 1's, d[2] 2's ..., d[9] 9's, and seeing what is the minimum factor of 11 that he could get by using all these digits, together with any number of 0's. Please help him figure out how many digits there are in this minimum factor. If he will not be able to form a multiple of 11 in this way, print -1.
INPUT
The first line will contain the number of test cases T. T lines follow one corresponding to each test case.
Each line has 9 integers d[1] d[2] .... d[9].
OUTPUT
Output T lines one corresponding to each test case. The ith line should contain the required answer for the corresponding test case.
CONSTRAINTS
1 <= T <= 100
1 <= d[1] + ... + d[9] <= 100
SAMPLE INPUT
2
2 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 1
SAMPLE OUTPUT
2
3
EXPLANATION
For the first case, the number 11 can be formed which has 2 digits.
For the second case, number 209 can be formed which is divisible by 11 and has 3 digits. | 32,215 |
Stocks Prediction (AMR10E)
The department store where my family goes shopping is trying to predict how much of each item they stock they will sell each month. Keeping a large amount of inventory is costly, and running out of items is also not a good idea. Since the manager asked for my help as a sales consultant, I decided to formulate a model for predicting each month's sales S of an item based on its sales during the previous R months. After a lot of trial and error, I came up with such a model, where
S(n) = a1*S(n-1) + a2*S(n-2) + ... + aR*S(n-R)
where S(n) is the predicted sales for the nth month for n > R, and S(1) to S(R) are seed values.
The store manager was pleased with my model's ability to help him in controlling his inventory.
He asked me to list out every Kth month's sales, and give him the sum of the first N values from this list. For example he wanted every Christmas month's sales summed up for the next 10 years (N=10 and K=12, month 1 being January), or every end-of-quarter month's sales for the next 2 years (N=2, K=3).
Can you please help me write a program that does all the above?
INPUT
The first line of the input T, the number of test cases. Each test case consists of three lines.
The first line of each test case contains N, R, K.
The second line of each test case contains R integers denoting S(1), S(2), ..., S(R).
The third line of each test case contains R integers denoting the coefficients a1, a2, ..., aR of the predictive model.
OUTPUT
For each test case, output the sum requested by the manager as given in the problem statement, modulo 1,000,000,007.
CONSTRAINTS
T <= 40
1 <= N <= 1000000000
1 <= R <= 8
1 <= K <= 8
0 <= All other input values < 1000000007
SAMPLE INPUT
2
4 1 1
1
2
3 2 3
1 1
1 1
SAMPLE OUTPUT
15
44
EXPLANATION
In the first test case, it is given that S(1) = 1 and the relation is S(n)=2*S(n-1). The list asked by the store manager consists of all the terms of S since K is 1. Hence, the answer is just the sum of the first 4 terms of S.
In the second test case, the sequence S is the fibonacci sequence which is: 1, 1, 2, 3, 5, 8, 13, 21, 34. The list consists of 2, 8, 34 which sum up to 44. | 32,216 |
Christmas Play (AMR10G)
My kid's kindergarten class is putting up a Christmas play. (I hope he gets the lead role.) The kids are all excited, but the teacher has a lot of work. She has to produce costumes for a scene with K soldiers. She wants to buy all the costumes in the same size, allowing for some small amount of length alteration to be done by the kids' parents later. So she has taken all the kids' height measurements. Can you help her select K kids from her class of N to play the soldier role, such that the height difference between the tallest and shortest in the group is minimized, and alternations will be easiest? Tell her what this minimum difference is.
Input
The first line contains the number of test cases T. T test cases follow each containing 2 lines.
The first line of each test case contains 2 integers N and K. The second line contains N integers denoting the height of the N kids.
Output
Output T lines, each line containing the required answer for the corresponding test case.
Constraints
T ≤ 30
1 ≤ K ≤ N ≤ 20000
1 ≤ height ≤ 1000000000
Example
Input:
3
3 1
2 5 4
3 2
5 2 4
3 3
2 5 4
Output:
0
1
3
Explanation
In the first test case, the teacher needs to only select 1 kid and hence she can choose any kid since the height difference is going to be 0.
In the second test case, the teacher can choose kids with height 4 and 5.
In the third test case, the teacher is forced to choose all 3 kids and hence the answer = 5-2 = 3 | 32,217 |
Shopping Rush (AMR10H)
A shop-keeper is trying to figure out how to arrange gifts in his shop for Christmas. He runs a peculiar shop such that each customer buys exactly two gifts at the shop (he could buy two of the same gifts too). He knows the probability that a customer might want gift i, is P_i.
He needs to arrange the gifts across several floors. Each floor should have exactly one gift. It takes A*(|x - y|)^2 + B*(|x - y|) + C seconds to go from floor x to floor y.
Can you help him arrange the gifts across floors such that, the expected time spent by a shopper is minimized?
For the purpose of this problem assume that the first gift choice and the second gift choice are independent of each other. i.e., Choosing a first gift as i does not change his probability of choosing the second gift as j. It still remains P_j.
INPUT
The first line contains the number of test cases T. 2*T lines follow, 2 per test case. The first line contains 4 integers : N, A, B, C. The second line contains N integers in the range 1 to 100. The ith integer represents the percentage probability P_i. All P_i's will sum to 100.
OUTPUT
Output T lines one for each test case. Each line contains the minimum expected travelling time for the corresponding test case. Output the answer as a reduced fraction as below.
CONSTRAINTS
1 <= T <= 100
1 <= N <= 20
0 <= A,B,C <= 10
SAMPLE INPUT
4
3 0 1 0
60 10 30
1 1 1 0
100
1 1 1 3
100
4 3 7 2
25 25 25 25
SAMPLE OUTPUT
3/5
0/1
3/1
73/4 | 32,218 |
Dividing Stones (AMR10I)
There are N stones, which can be divided into some piles arbitrarily. Let the value of each division be equal to the product of the number of stones in all the piles modulo P. How many possible distinct values are possible for a given N and P?
Input
The first line contains the number of test cases T. T lines follow, one corresponding to each test case, containing 2 integers: N and P.
Output
Output T lines, each line containing the required answer for the corresponding test case.
Constraints
T ≤ 20
2 ≤ N ≤ 70
2 ≤ P ≤ 1e9
Example
Input:
2
3 1000
5 1000
Output:
3
6
Explanation
In the first test case, the possible ways of division are (1, 1, 1), (1, 2), (2, 1) and (3) which have values 1, 2, 2, 3 and hence, there are 3 distinct values.
In the second test case, the numbers 1 to 6 constitute the answer and they can be obtained in the following ways:
1 = 1 × 1 × 1 × 1 × 1
2 = 2 × 1 × 1 × 1
3 = 3 × 1 × 1
4 = 4 × 1
5 = 5
6 = 2 × 3 | 32,219 |
Mixing Chemicals (AMR10J)
There are N bottles each having a different chemical. For each chemical i, you have determined C[i] which means that mixing chemicals i and C[i] causes an explosion. You have K distinct boxes. In how many ways can you divide the N chemicals into those boxes such that no two chemicals in the same box can cause an explosion together?
INPUT
The first line of input is the number of test cases T. T test cases follow each containing 2 lines.
The first line of each test case contains 2 integers N and K.
The second line of each test case contains N integers, the ith integer denoting the value C[i]. The chemicals are numbered from 0 to N-1.
OUTPUT
For each testcase, output the number of ways modulo 1,000,000,007.
CONSTRAINTS
T <= 50
2 <= N <= 100
2 <= K <= 1000
0 <= C[i] < N
For all i, i != C[i]
SAMPLE INPUT
3
3 3
1 2 0
4 3
1 2 0 0
3 2
1 2 0
SAMPLE OUTPUT
6
12
0
EXPLANATION
In the first test case, we cannot mix any 2 chemicals. Hence, each of the 3 boxes must contain 1 chemical, which leads to 6 ways in total.
In the third test case, we cannot put the 3 chemicals in the 2 boxes satisfying all the 3 conditions. | 32,220 |
The area of the union of circles (CIRU)
You are given N circles and expected to calculate the area of the union of the circles!
Input
The first line is one integer n indicates the number of the circles. (1 ≤ n ≤ 1000)
Then follows n lines every line has three integers
Xi Yi Ri
indicates the coordinate of the center of the circle, and the radius. (|Xi|. |Yi| ≤ 1000, Ri ≤ 1000)
Note that in this problem Ri may be 0 and it just means one point !
Output
The total area that these N circles with 3 digits after decimal point
Example
Input:
3
0 0 1
0 0 1
100 100 1
Output:
6.283 | 32,221 |
God of Number Theory (NUMG)
In ACM_DIY, there is one master called “ShaZai”. As we know, he is the god of “Number Theory”. He always kills the problem about “Number Theory” in seconds! But of course we do not have any idea about these problems. One day in ACM_DIY, ShaZai asks us one problem:
You are given three non-negative integers A, B and K, you are expected to find the number of numbers that satisfy:
X
A
= B (mod (2K + 1))
X is in the range [0, 2K];
Of course we have no idea about this problem, so could you help us?
Input
The first line is one integer T indicates the number of the test cases. (T ≤ 1000)
Then for every case, only one line contains three integers A, B and K. (1 ≤ A, B ≤ 10
9
, 1 ≤ K ≤ 5 × 10
8
)
Output
Output the answer in a single line.
Example
Input:
3
213 46290770 80175784
3 46290770 80175784
3333 46290770 80175784
Output:
27
27
297 | 32,222 |
Sequence (SEQN)
As you know, the number of permutation of the increasing vector {1, 2, 3 … n} is exactly n! For example, if n = 3, then, {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1} are all the permutation of the vector {1, 2, 3};
We define D( {
A1, A2 ... An
} ) = the number of element that satisfy Ai = i.
For example, D( {1, 2, 3} ) = 3, D( {1, 3, 2} ) = 1 (only ‘1’ is at 1), D({3, 1, 2}) = 0 ….
Now we want to calculate the number of permutation that satisfy D( {A1, A2 ... An } ) = K.
For example, if n = 3 and k = 3, then of course there is only one permutation {1,2,3} that satisfy D( {1, 2, 3}) = 3. But if n = 3 and k = 0, then there are two permutations {3, 1, 2} and {2, 3, 1} satisfy D( {3, 2, 1} ) = D( {2, 3, 1} ) = 0;
But when n is very large, it’s hard to calculate by brute force algorithm. Optimal is one required here.
Because the answer may be very large, so just output the remainder of the answer after divided by m.
Input
In the first line there is an integer T, indicates the number of test cases. (T <= 500)
In each case, the first line contains three integers n, k and m. (0 <= k<= n <=10^9, 1 <= m <= 10^5, n != 0)
Output
Output “Case d: “first where d is the case number counted from one. Then output the remainder of the answer after divided by m.
Example
Input:
3
3 0 7
3 3 3
331105236 82934100 3711
Output:
Case 1: 2
Case 2: 1
Case 3: 2622 | 32,223 |
Sevenk Love Oimaster (JZPGYZ)
Oimaster and Sevenk love each other.
But recently, Sevenk heard that a girl named ChuYuXun was dating with Oimaster.
As a woman's nature, Sevenk felt angry and began to check Oimaster's online talk with ChuYuXun. Oimaster talked with ChuYuXun n times, and each online talk actually is a string. Sevenk asks q questions like this, "how many strings in Oimaster's online talk contain this string as their substrings?"
Input
There are two integers in the first line, the number of strings n and the number of questions q. And n lines follow, each of them is a string describing Oimaster's online talk. And q lines follow, each of them is a question. n <= 10000, q <= 60000 the total length of n strings <= 100000, the total length of q question strings <= 360000
Output
For each question, output the answer in one line.
Example
Input:
3 3
hi,I'mChuYuXun..YouaresohandsomethatIfallinlovewithyou
butIloveSevenk..you'dbettergoaway
55555555555
ChuYuXun
you
55555555
Output:
1
2
1 | 32,224 |
Islands (IOIISL08)
You are visiting a park which has
N
islands. From each island i, exactly one bridge was constructed. The length of that bridge is denoted by
Li
. The total number of bridges in the island is
N
. Each bridge can be traversed in both directions. Also, for each pair of islands, there is a unique ferry that travels back and forth between them.
Since you like walking better than riding ferries, you want to maximize the sum of the lengths of the bridges you cross subject to the constraints below :
You can start a visit on an island of your choice.
You may not visit any island more than once.
At any time you may move from your current island S to any island D which you have not visited before. You can go from S to D either by walking, in which case the length of the bridge you take will be added to the total length or by ferry if the islands are not connected by any bridge (when checking for connectivity you should include those islands which have been previously visited by you).
Note that you do not have to visit all the islands, and it may be impossible to cross all the bridges.
Given N bridges along with their lengths, your task is to find out the maximum distance you can walk by following the rules above.
Constraints
2 ≤ N ≤ 100000
1 ≤ Li ≤ 1000000
Input
The first line of the input contains N, the number of islands. Islands are numbered 1 to N inclusive. Then follow N lines. The ith of these lines contains two integers Ii and Li, which are the island the ith island connects to and the length of the bridge respectively. You may assume that each bridge has two different islands as its endpoints.
Output
You must write a single line which is the maximum possible distance that you can walk.
Example
Input:
7
3 8
7 2
4 2
1 4
1 9
3 4
2 3
Output:
24
Explanation of the Example
Start at 5.
Walk to 1.
Walk to 3.
Walk to 6.
Ferry to 7.
Walk to 2.
Hence total distance you walked is 9 + 8 + 4 + 3 = 24.
Note:
The final answer fits within 64 bit integer. | 32,225 |
Crash´s number table (TABLE)
In today's math lesson, Little Crash has just learnt Least Common Multiple (LCM). For two positive integers
a
and
b
, LCM(
a
,
b
) means the minimum positive integer which can be divisible by
a
and
b
.
After coming home, Crash is still thinking about what he learnt in the math lesson. Then he draw a table filled numbers in order to research LCM. The table has
N
rows and
M
columns. The number in the
i
th row and
j
th column is LCM(
i
,
j
).
A table of 4*5 is just like this:
1
2
3
4
5
2
2
6
4
10
3
6
3
12
15
4
4
12
4
20
Now Little Crash wants to know the sum of all the numbers in the table. You just need to output the sum modulo 20101009.
Input
Only two positive integers stand for
N
and
M
. (
N
,
M
<= 10
7
)
Output
A positive integer which means the sum modulo 20101009.
Example
Input:
4 5
Output:
122 | 32,226 |
Shifting Lights (SHLIGHTS)
Recently I made a new device. It contains a set of lightbulbs, each having two parts. The left part glows blue and the right part glows green. One cannot guess which parts of the bulbs will be glowing when the device is powered on. Consider any two adjacent bulbs at time t. If the left bulb is glowing green and the right bulb is glowing blue they swap their states to blue and green respectively at time t + 1. But now I am wondering, if I
power it on
when will the bulbs stop swapping. Can you help me with this ?
Input
The first line of the input contains t, the number of testcases. Each of the next t lines contains a single string containing characters 'B' and 'G' representing the bulbs when switched on i.e. at time t = 0. Here 'B' is for blue and 'G' is for green. The length of the
string will be less than 100000.
Output
For each test output one line giving the time after which swapping stops.
Example
Input :
2
GBGBBB
BGBBGGGBBBGBGB
Output :
4
8 | 32,227 |
Friendly Knights (KFRIENDS)
Gurram land is the city of knights and is shaped exactly like a chess board. Some of the cells in this city contains knights. Due to scarcity of grass (Global Warming!), there have been fights between every pair of neighboring knights. Knight A is a neighbor of knight B, if A can reach B in exactly one step (see notes for clarity).
To spread peace in the Gurram land, the United Nations has organized a 'Friendship Mela' and wants to distribute friendship neck straps to the knights. Each pair of neighboring knights then exchange neck strap of same color and wear it around their neck, to promote friendship :). To make it more colorful, the UN also wants each knight to have distinct colored neck straps around its neck. The UN is ready to produce any number of straps of a particular color, but can you help them to find out the minimum number of colors to be used.
Notes:
A knight in cell (x, y) can move in one step to any of the cells (x+2, y+1), (x+2, y-1), (x+1, y+2), (x+1, y-2), (x-2, y+1), (x-2, y-1), (x-1, y+2), (x-1, y-2) i.e., the normal rule in standard chess.
Input
First line contains T (around 10), the number of test cases. Each test case starts with an integer N (0 ≤ N ≤ 10000) the number of knights in the city. Each of the next N lines contains two integers X Y the row and the column number of a knight (1 ≤ X, Y ≤ 100). No two knights are on a same cell.
Output
For each test case, print the minimum number of colors needed, in a separate line.
Example
Input:
2
3
1 1
2 3
3 2
4
1 1
2 3
2 1
1 3
Output:
2
1
Case 1 : (1, 1) and (2, 3) can exchange a Red strap, (1, 1) and (3, 2) can exchange a Green Strap.
Case 2 : (1, 1) and (2, 3) can exchange a Red strap, (2, 1) and (1, 3) can exchange a Red Strap. | 32,228 |
Dot Product Maximization (DPMAX)
Given two vectors, a = ( x
a
, y
a
), b = ( x
b
, y
b
), their dot product is defined as follows:
dp( a, b ) = x
a
*x
b
+ y
a
*y
b
.
Given N vectors in the plane, find a pair for each of them (among those given in the input) such that the dot product of the vector and its pair is maximal. You may pair a vector with itself too.
Input
The first line of input contains a single integer N ( 1 <= N <= 200000 ).
Each of the next N lines contain a pair of real numbers, x
i
and y
i
(0 <= |x
i
|, |y
i
| <= 100000)
,
representing the i-th vector. x
i
and y
i
will be rounded to 3 decimal places.
Output
Output N lines, i-th one containing the maximal dot product for the i-th vector from the input rounded to 3 decimal places.
Example
Input:
4
0.000 1.000
0.000 2.000
1.000 1.000
0.000 0.000
Output:
2.000
4.000
2.000
0.000
Explanation:
Pair the first vector with the second, the second with itself, third with itself or with the second, and the last one with any of them. | 32,229 |
Normalized Form (ACPC10C)
As you most probably know, any boolean expression can be expressed in either a disjunctive normal form or a conjunctive normal form. In a disjunctive normal form, a boolean expression is written as a disjunct (logical or) of one-or more sub-expressions where each of these sub-expressions is written in a conjunctive normal form. Similarly, an expression written in a conjunctive normal form is a conjunct (logical and) of sub-expressions each written in a disjunctive normal form.
An AND/OR tree is a tree-like graphical-representation of boolean ex- pressions written as either conjunctive- or disjunctive-normal form. Since the sub-expressions of a normalized form alternate in being either disjunctive or conjunctive forms, you’d expect the sub-trees on an AND/OR tree to alternate in being AND- or OR- trees depending on the sub-tree’s depth-level. The example upwards illustrates this observation for the boolean expression (A (B C)) (D E) where the trees in the 1st (top-most) and 3rd levels are AND-trees.
Write a program that evaluates a given and/or tree.
Input
Your program will be tested on one or more test cases. Each test case is specified on exactly one line (which is no longer than 32,000 characters) of the form:
( E1 E2 . . . En )
where n > 0 and Ei is either T for true, F for false, or a sub-expression using the same format.
The trees at the deepest level are AND-trees. The last test case is followed by a dummy line made of ().
Output
For each test case, print the following line:
k. E
Where k is the test case number (starting at one,) and E is either true or false depending on the value of the expression in that test case.
Example
Input:
((F(TF))(TF))
(TFT)
((TFT)T)
()
Output:
1. false
2. false
3. true | 32,230 |
POLYU (POLYU)
In the country of Giantarum, the king of Giantarum is AC. AC and his billions of hougong like to eat giantarum very much. The shape of giantarum is special! It could be regard as a triangle. There are N giantarums in the Cartesian coordinates, they may cover each other. AC wants to know the total area that is covered by giantarums.
Input
In the first line there is an integer T, indicates the number of test cases. (T ≤ 100)
In each case, the first line contains an integer N (N ≤ 100), indicates the number of the giantarum. The follow N line, every line contains six floating numbers x0, y0, x1, y2, x2, y2, indicates the coordinate of the three vertices of the giantarum. (all |xi| ≤ 10
4
and |yi| ≤ 10
4
)
Output
For every test case, output one line. First output “Case idx: ”, here idx is the case number start from 1.Then output the area, rounded to 3 digits after the decimal point.
Example
Input:
2
1
0 0 1 0 1 1
2
0 0 1 0 1 1
0 0 0 1 1 1
Output:
Case 1: 0.500
Case 2: 1.000 | 32,231 |
CIRU2 (CIRUT)
You are given N
different
circles, while some region may be covered more than once.
If one region is covered by K times, then it was called a "K- Region".
So, you are expected to output the area of all the regions! (K from 1 to N)
Input
The first line is one integer n indicates the number of the circles. (1 <= n <= 1000)
Then follows n lines every line has three integers
Xi Yi Ri
indicates the coordinate of the center of the circle, and the radius. (|Xi|. |Yi| <= 1000, 0 < Ri <= 1000)
Output
Output N lines, the i-th line output
[i] = area_of_i_region
here the area must round to 3 digits after decimal point.
Example
Input:
3
0 0 1
1 0 1
1 1 1
Output:
[1] = 4.699
[2] = 1.699
[3] = 0.443 | 32,232 |
Sky Lift (SKY)
We can represent a grid of skyscrapers by an NxN matrix of their positive heights. A skyscraper is made out of square blocks, and you may travel through them using a special elevator that can move as any other, but also sideways (four possible directions on a fixed floor). They may move anywhere as long as they don't exit the skyscrapers. In other words, if the elevator is inside a skyscraper, it may move to the neighboring skyscraper only if its height is greater or equal to the current level the elevator is at.
Moving sideways (in one of the 4 directions, that is, N, E, S, W...) is done for free when using this elevator, but moving one floor up or down costs exactly one unit.
Given the positions of two skyscrapers, find the cost of moving from the
top block
of the first to the
top block
of the second using the described elevator.
Input
The first line of input contains a single integer N ( 1 <= N <= 1000 ). The next line contains four integers, x
a
, y
a
, x
b
, y
b
, (between 1 and N), representing the positions of the two skyscrapers.
The next line contains three integers: A, B and C (1 <= A, B, C <= 10
9
).
Generate the height of the skyscraper at coordinates (i, j) using the formula h
ij
= (((i-1)*N+j-1)*A + B) mod C (indicies are 1-based).
Output
To the first and only line of input output the solution.
Example
Input:
3
1 1 3 3
5 5 7
Output:
2 | 32,233 |
Street Trees (STREETR)
A group of trees is planted along a straight line. KOI is planning to plant more trees so that the distance between two adjacent trees is equal for all trees.
For simplicity, each tree can only be planted on an integer coordinate.
For example, if 4 trees were originally planted on coordinates (1, 3, 7, 13), and if KOI plants 3 more trees on coordinates (5, 9, 11), then the distance between two adjacent trees will equal for all trees.
Your task is to calculate the minimal number of trees that KOI can plant so that the distance between two adjacent trees will equal for all trees.
Input
The first line is an integer N (3 ≤ N ≤ 100,000), which denotes the number of already planted trees.
The next N lines will have an integer X (1 ≤ X ≤ 1,000,000,000), which denotes the coordinate of each tree.
You can safely assume that the value of X will be unique.
Output
Output the minimal number of trees that must be planted.
Example
Input:
4
1
3
7
13
Output:
3
Input:
4
2
6
12
18
Output:
5
[Edited] Warning:
Some input file contains garbage at the end. | 32,234 |
Chairs (CHAIR)
N chairs are placed in a circle.
There will be K attendants to a very important meeting.
However, the attendants do not like each other, so they do not want to sit beside each other in the meeting.
As the host of this important meeting, you want to find out how many ways there are to choose K chairs such that none of them are adjacent to each other.
Input
The first line of the input is an integer N (4<=N<=1000), which denotes the number of chairs.
The next line is an integer K (1<=K<=N), which denotes the number of attendants to the meeting.
Output
Output the total number of ways to choose K chairs from N chairs such that none of the chairs are adjacent.
Since the answer can get very large, output the answer modulo 1,000,000,003.
Example
Input:
4
2
Output:
2 | 32,235 |
Beautiful numbers EXTREME (JZPEXT)
We call one integer beautiful, if and only if it is divisible by each of its non-zero digits. Given an interval [l, r], calculate how many beautiful numbers n satisfy l ≤ n ≤ r.
Input
First line, the number of test cases, t.
Then t lines follow, each line two numbers l, r, representing the query interval [l, r].
1 ≤ t ≤ 2.5×10
4
1 ≤ l ≤ r ≤ 10
18
Output
t lines. The t-th line is the answer to the t-th query.
Example
Input:
1
1 100
Output:
33 | 32,236 |
Bureaucracy (BUREAU)
Many centuries later lawyers discovered that there were only two types of laws in the kingdom:
² direct law, that states a new norm;
² canceling law, that cancels one of the previous laws.
The law is considered active if and only if there is no active law that cancels it.
You are to write program that ¯nds out which laws are still active.
Long ago, in a kingdom far, far away the king decided to keep a record of all laws of his kingdom. From that moment whenever a new law was passed, a corresponding record was added to the law archive.
Many centuries later lawyers discovered that there were only two types of laws in the kingdom:
direct law, that states a new norm;
canceling law, that cancels one of the previous laws.
The law is considered active if and only if there is no active law that cancels it.
You are to write program that finds out which laws are still active.
Input
The first line of the input contains T, the number of test cases. T test cases follow.
The first line of each test case contains an integer number n (1 <= n <= 100000) - the number of passed laws.
The following n lines describe one law each. Each description has one of the following formats:
"declare", meaning that a direct law was passed.
"cancel i", where i is the number of law being cancelled by this one.
The laws are numbered from one.
Output
For each test case your output must contain a line with the number of active laws. The following line must contain numbers of these laws listed in increasing order.
Example
Input:
1
5
declare
cancel 1
declare
cancel 2
cancel 3
Output:
3
1 4 5 | 32,237 |
Circles On A Screen (CIRCSCR)
Yesterday Andrew wrote a program that draws n white circles on a black screen. The screen is monochrome and it has a resolution w x h pixels. Pixels are numbered from upper left corner (0, 0) to bottom right one (w-1, h-1).
A circle with the center at pixel (x
c
, y
c
) and the radius r consists of the pixels with coordinates (x, y) such that (x
c
-x)
2
+ (y
c
-y)
2
<= r
2
. If the circle does not fit on the screen, it is truncated. If some pixel belongs to two or more circles, it is white.
The resulting picture was very nice, so Andrew decided to copy it to his wall. He has white wallpaper and he can only draw some parts of wall into black. Now he wants to know the amount of paint he needs.
He copies the picture exactly pixel-to-pixel, so you should write a program that calculates the number of black pixels left on a screen after drawing n circles.
Input
In the first line of input file there is an integer T, the number of test cases. T test cases follow.
Each test case begins with a line where there are three integers: w, h, and n (1 <= w, h <= 20.000; 1 <= n <= 100). Each of the following n lines contains descriptions of the circles. In i+1-th line there are three integers: x
i
, y
i
, r
i
(0 <= x
i
< w; 0 <= y
i
< h; 0 <= r
i
<= 40 000). They denote a circle with the center at pixel (x
i
, y
i
) and radius r
i
.
Output
For each test case you should output exactly one number - the number of black pixels left on the screen.
Example
Input:
2
5 3 2
1 1 1
3 1 1
12 9 2
3 3 2
7 5 4
Output:
6
51
Note: The picture corresponds to the second test case of the example. | 32,238 |
XOR Maximization (XMAX)
Given a set of integers S = { a
1
, a
2
, a
3
, ... a
|S|
}, we define a function X on S as follows:
X( S ) = a
1
^ a
2
^ a
3
^ ... ^ a
|S|
.
(^ stands for bitwise 'XOR' or 'exclusive or')
Given a set of N integers, compute the maximum of the X-function over all the subsets of the given starting set.
Input
The first line of input contains a single integer N, 1 <= N <= 10
5
.
Each of the next N lines contain an integer a
i
, 1 <= a
i
<= 10
18
.
Output
To the first line of output print the solution.
Example
Input:
3
1
2
4
Output:
7 | 32,239 |
Substrings (NSUBSTR)
You are given a string S which consists of 250000 lowercase Latin letters at most. We define F(x) as the maximal number of times that some string with length x appears in S. For example for string 'ababa' F(3) will be 2 because there is a string 'aba' that occurs twice. Your task is to output F(i) for every i so that 1 ≤ i ≤ |S|.
Input
String S consists of at most 250000 lowercase Latin letters.
Output
Output |S| lines. On the i-th line output F(i).
Example
Input:
ababa
Output:
3
2
2
1
1 | 32,240 |
N-Factorful (NFACTOR)
A number is called
n
-factorful if it has exactly
n
distinct prime factors. Given positive integers
a
,
b
, and
n
, your task is to find the number of integers between
a
and
b
, inclusive, that are
n
-factorful. We consider 1 to be 0-factorful.
Input
Your input will consist of a single integer
T
followed by a newline and
T
test cases. Each test case consists of a single line containing integers
a
,
b
, and
n
as described above.
T
> 10000
1 ≤
a
≤
b
≤ 10
6
0 ≤
n
≤ 10
Output
Output for each test case one line containing the number of
n
-factorful integers in [
a
,
b
].
Example
Input:
5
1 3 1
1 10 2
1 10 3
1 100 3
1 1000 0
Output:
2
2
0
8
1 | 32,241 |
Big Pyramid (EMILABC)
Archeologists have discovered an ancient manuscript describing a big pyramid. The pyramid is built of cubical stone blocks as shown in the picture. There are
N
horisontal levels in the pyramid. The topmost level consists of a single block, and the base level is a square of
2*N-1×2*N-1
blocks. The archeologists learned from the manuscript the size of a stone block and the orientation the pyramid. However, they do not know the size and the exact location of the pyramid.
There are many hills in the land where the pyramid is believed to be located. The archeologists think that one of the hills is actually the pyramid covered with sand. To check that hypothesis, they produced an elevation map of the land. The land was divided into a grid of
H×W
cells. The size of a cell is the same as the size of a stone block face. For each cell they measured its height and calculated how many stone blocks can be underneath the surface of the cell.
Now the archeologists give you the elevation map and ask to compute the largest possible pyramid size, assuming that the pyramid base sides are parallel to the grid lines.
Input
The first line of the input contains two integers
H
and
W
(
0 < H, W ≤ 200
).
Each of the subsequent
H
lines contains
W
integers. Each integer is non-negative and less than 201.
Output
One interger - the number of levels in the larget possible pyramid.
Example
Input:
5 6
0 0 0 0 0 0
0 1 0 0 0 0
0 0 1 1 1 1
0 0 1 1 2 1
0 0 1 1 1 1
Output:
2 | 32,242 |
Zero Count (ZEROCNT)
Write down N integers 1, 2 ... N in binary system on a paper, one per line, ignore all leading 0s:
1
10
11
100
101
110
111
...
Now on each line, consider all groups of consecutive 0s, index these group from 1. We will color all zeros in the 1st, (K+1)th, (2K+1)th, ... group, for K is a given integer.
For example: if a number in binary is: 1
0
1000111
00
110000, and K = 2. We have 4 groups of consecutive 0s, and we will color all zeros in the 1st and the 3rd group. So we will color 1 + 2 = 3 zeros in this line.
Given N and K. Compute total number of 0s we will color in the paper. (The paper is big enough to contain all numbers :D)
Input
Several lines, each line contains 2 integers: N and K separated by a single space. (1 < N < 2
31
, K > 0)
Output
For each line in the input, print exactly 1 number on a single line which is the result of the corresponding test case.
Example
Input:
4 1
56 2
Output:
3
92 | 32,243 |
Number of Prime Strings (PSTR)
A string is called a "prime string" if it can't be written as concatenation of more than one same strings. For example, the following strings are not prime strings: AAA, ABABAB, CFGFGCFGFG, while CFGFGC, ABABA are prime strings.
Calculate the number of prime string of length N (1<=N<=1000000), and only contains first K (1<=K<=26) letters from English alphabet. Note that some of these K letters need not appear in that string.
Input
Multiple test cases. The number of them (about 10000) is given in the very first line.
Each test case contains one line with two integers - K and N, separated by a single space.
Output
For each test case, output the required number modulo 1000000007 in a single line.
Example
Input:
1
2 3
Output:
6
Explanation
The prime strings of length 3 which only contain character 'A' and 'B' are: AAB, ABA, ABB, BAA, BAB, BBA.
Constraints
1 <= N <= 1000000
1 <= K <= 26
Total number of test cases is around 10000. | 32,244 |
Combination Of Integers (INTCOMB)
You will be given n positive integers a
1
, a
2
... a
n
. We say that a non-negative integer combination of these numbers is of the form a
1
*b
1
+ a
2
*b
2
+ ... + a
n
*b
n
where each of b
1
, b
2
... b
n
is a non-negative integer. You are to determine how many positive integers cannot be expressed as a non-negative integer combination of a
1
, a
2
... a
n
.
Input
The first line contains a single integer denoting the number of test cases (about 30). Each test case consists of a single line. The first integer on the line is n, between 1 and 30, which indicates the number of integers a
1
, a
2
... a
n
. Then n integers follow each between 1 and 100, 000. The i'th such integer is a
i
. All integers on this line are separated by a space.
Output
For each test case you are to output a single line. If there are only a finite number of positive integers that cannot be expressed as a non-negative integer combination of a
1
, a
2
... a
n
, then you are to output this number. Otherwise, simply output the text "Infinite" (without quotes).
Constraints
1 <= n <= 30
1 <= a
i
<= 100000
Example
Input:
3
2 2 4
2 4 5
3 11 12 13
Output:
Infinite
6
30
Explanation
Sample Test 2:
You cannot express 1, 2, 3, 6, 7 and 11 using only the integers 4 and 5. | 32,245 |
Distance (DIST)
You are given the coordinates of N cities (x
i
, y
i
). Each city also has a popularity value, p
i
. You have to place a new city (x, y) such that the sum of distances of this new point from all the other given points is minimized.
Distance of the new point from a given city i is given by:
d = |x
i
- x|
p
i
+ | y
i
- y |
p
i
Input
The first line contains the number of test cases.
Each test case starts with the number N, the number of points. This is followed by the descriptions of each in the format
x
i
y
i
p
i
. The input consists of only integers.
Output
For each test case, output the minimum distance obtained, with exactly 3 digits after the decimal point.
Example
Input:
1
3
1 2 0
4 5 1
2 4 2
Output:
4.500
Constraints
Number of test cases ≤ 10
N ≤ 10
5
|x
i
, y
i
| ≤ 1000
0 ≤ p
i
≤ 3 | 32,246 |
Non-Decreasing Numbers (NONDEC)
A Non-Decreasing number is a number whose ith digit from the left is greater than or equal to the (i-1)th digit from the left.
You are given four integers A, B, C and D. X is any integer between A and B, inclusive, and Y is any integer between C and D, inclusive. You must output the number of numbers formed by the concatenation of X and Y which are Non-Decreasing, i.e. if we treat "X" and "Y" as STRINGS, then "Z" = "X" + "Y" must represent a Non-Decreasing number.
Since this number can be very large, give your answer modulo 98765431.
If the same number "Z" can be formed in various ways, it must be counted every time. See example for clarification.
Input
The first line of the input contains t, the number of test cases. This is followed by t lines containing 4 positive integers each, which are the values of A, B, C, D.
Output
You must output t lines. Each line contains the answers for the quadruple (A, B, C, D) in the order they appear in input.
Example
Input:
1
1 11 1 11
Output:
56
Explanation
Note that the number "111" is counted twice. Once as "11" + "1" and again as "1" + "11".
Constraints
A, B, C, D are all positive integers having ≤ 1000 digits
A ≤ B; C <= D;
Number of test cases t ≤ 1000 | 32,247 |
Weighted Sum (WEIGHT)
You are given N integers, A[1] to A[N]. You have to assign weights to these integers such that their weighted sum is maximized. The weights should satisfy the following conditions :
Each weight should be a positive integer.
W[1] = 1
W[i] should be in the range [2, W[i-1] + 1] for i > 1
Weighted sum is defined as S = A[1] × W[1] + A[2] × W[2] + ... + A[N] × W[N]
Input
There are multiple test cases.
First line contains the number of test cases
Each test case consists of a single line containing N.
This is followed by N lines, each containing A[i]
Output
For each test case, output one line - the maximum weighted sum.
Example
Input:
1
4
1
2
3
-4
Output:
6
Explanation
The weights are 1, 2, 3, 2.
Constraints
N ≤ 10
6
| A[i] | ≤ 10
6
Total number of test cases is around 10. | 32,248 |
Rectangles in a Matrix (RECTMAT)
In a matrix with n rows and m columns, (i, j) is the cell in i-th row and j-th column (0 ≤ i < n, 0 ≤ j < m). A rectangle (r0, r1, c0, c1) in a matrix is the set of cells (i, j) where r0 ≤ i < r1 and c0 ≤ j < c1. (0 ≤ r0 < r1 ≤ n, 0 ≤ c0 < c1 ≤ m). Two rectangles are called independent if the intersection of their cell set is empty.
Given n, m, k, find the number of ways to choose k independent rectangles from a n×m matrix. The order of these k rectangles doesn't matter, see sample for further clarification.
Input
One line contains three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 6).
Output
For each test case, output the number of ways, modulo 10
9
+7.
Example
Input:
2 2 4
10 10 1
Output:
1
3025
Explanation
First case: You have to find the number of ways of choosing 4 independent rectangles from a 2×2 matrix.
The only way to do this is to choose each cell as a separate rectangle.
Constraints
(1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 6).
Total number of test cases is around 150. Not all the test cases are included. | 32,249 |
Perfect Matching (MATCH)
You are given a bipartite graph with N (1 <= N <= 300) nodes on each side. Determine whether the number of perfect matching is odd or even.
Input
First line is an integer T(1<=T<=20) means the number of test cases. The following are T parts. Each part begin with an integer N(1<=N<=300) means the number of nodes on both sides. It followed with N lines, each line contains a 0/1 string. If the j th (1 <= j <= N) character of the i th (1 <= i <= N) line is 1, it means the i th node on left have an edge to the j th node on right. See the sample for details.
Output
T lines, each contain "Odd" or "Even", which means the parity of the number of the perfect matching. See the sample for details.
Example
Input:
2
1
1
4
1100
1100
0011
0011
Output:
Odd
Even
Constraints
1 <= N <= 300
1 <= T <= 20 | 32,250 |
Fast Food Restaurant (FASTFOOD)
Hong Kil Dong wants to open a new fast food restaurant to make some money. The picture below describes the city where he wants to open his restaurant. The nodes are the possible locations that he can set up his new restaurant, and the edges are the length of the road connecting the two locations. You can assume that maximum five roads intersect at a single node, and that it is possible to reach all nodes from any chosen node.
There are three apartments (these three are the only places people live in) in this city, denoted A, B, and C, as shown in the picture.
Suppose he wants to open his new restaurant in location (node) 1. The shortest distances from location 1 to A, B, and C are 8, 16, and 9 respectively. These values are each larger than the shortest distances from location 4 to A, B, and C, which are 6, 7, and 3. Since people usually prefer using closer restaurants, it is better to open his restaurant in location 4.
Consider location 6. The shortest distances from location 6 to A, B, and C are 5, 3, and 5. Therefore, location 6 is better than location 1. However, when comparing with location 4, it is better regarding A and B, but worse when considering C.
Therefore, Hong Kil Dong came up with a criteria to determine whether a given location is good or bad.
Consider location p, and let the shortest distances from location p to A, B, and C be a, b, and c, respectively.
Consider another location q, and let the shortest distances from location q to A, B, and C be x, y, z, respectively.
If a>x, b>y and c>z, we say that location p is a bad location. If there is no location q that satisfies this, we say that location p is a good location.
Hong Kil Dong has chosen some candidate locations. Given the description of the city and a number of queries, determine whether each candidate location is good or bad.
Note that it is possible to open the restaurant in any of the locations, even in A, B, and C.
Input
The first line of the input is an integer N (1<=N<=100,000), denoting the number of locations. All the locations are numbered from 1-N.
The second line of the input is three integers A, B, and C, denoting the location of each apartment. A, B, and C are all distinct and are between 1 and N, inclusive.
The third line of the input is M, denoting the number of roads in this city.
The next M lines give the description of each road and consist of integer X, Y, and Z (1<=Z<=10,000). X and Y are the two endpoints of this road, and Z is the length of this road. No two same roads appear in the input.
The next line is an integer T (1<=T<=10,000), denoting the number of queries.
The next T lines each consist of an integer Q (1<=Q<=N), which denote the location number.
Output
For each query, determine whether location Q is a good location or a bad location. If it is bad, output "NO" (quotes for clarity) and "YES" if it is good.
Example
Input:
9
2 5 9
15
1 2 8
1 3 5
2 4 6
2 5 8
2 6 5
3 4 6
3 9 4
4 6 4
4 9 3
5 6 3
5 7 4
6 7 2
6 9 5
7 8 7
8 9 6
2
1
2
Output:
NO
YES | 32,251 |
Win gold medal (WINGOLD)
In a game there are infinite number of levels. In order to go to the next level, a player has to clear all the preceding levels. A player cant go further, if he fails to clear the level. Each player has a probability p of clearing the level (which is independent of the other players and the level number). For example, if p =1/2 there is a probability 2^(-n-1) that a particular game will have exactly n levels cleared. A player will get Gold medal if he clears the maximum number of levels. If the maximum number of levels reached is common between two or more players, then no one wins the gold medal. What is the probability that a Gold medal is given to any player?
Input
T number of test cases each case follow
p n m . probability of clearing level for each player, number of player, number of levels in game
Output
T line each probability that gold medal is given round off to 4 significant digits
limit:
1<=T<10000
1<=n<1000
1<=m<100
0<=p<=1.0
Example
Input:
6
0.43 3 2
0.5 3 4
0.2 3 4
0.1 4 5
0.9 3 3
1.0 4 4
Output:
0.4490
0.6244
0.4184
0.3014
0.0275
0.0000 | 32,252 |
Red Balls (SIGNGAME)
After the previous game ,each ball is either red or green in color. Dope tells you that he is changing the color of all balls in the range i to j (both inclusive),that is red balls to green and green balls to red. And then he asks you to tell the total extra mass of red balls over green balls for some range between i to j (inclusively). As you like red balls, you will try to maximize the total mass of red balls mass over the green balls. So He allows you to choose any range inside the range i, j inclusively which gives the maximum extra mass of red balls over the green balls. When you choose a range, you have to take all the green and red balls that belong to the range.
Convention:
(+) positive mass represents red ball mass
(-) negative mass represents green ball mass
Input
T number of test cases
next T test cases follow each contains:
N number of balls
next line contains N mass of ball (positive or negative)
next line Q number of operation and query next Q lines contain
c a b
c = 0 change the color of balls in range a, b inclusively
c = 1 print the maximum extra mass of red balls over green in the range a, b inclusively.
Output
each line for print query
limit:
1 <= T < 10
1 <= N < 100000
1 <= Q < 100000
0 <= a <= b < N
c = 0 or 1
abs(individual mass)<1000
Example
Input:
1
5
2 -3 4 5 -2
4
0 0 2
1 0 2
1 1 3
0 1 1
Output:
3
5
[you have to choose a range, if all balls are green in the range you have to print (-)ve answer] | 32,253 |
color the balls (PLAYSIGN)
You and Dope are visiting DAKSH. Suddenly Dope found some balls having some mass on it and all balls are white in color. They found an interesting thing of the balls that they can change color to either red or green on clicking the switch on it. Dope is in a funny mood and wants to play a game with you. He tells you that each player will switch the balls to either red or green color alternatively and only white ball can be chosen to change the color. After changing the color of all balls you need to pay an amount equal to the absolute difference between mass of the red balls and green balls. Dope would try to maximize the pay and obviously you want to give him as little as possible. Dope invites you to play first. If you and Dope play optimally, what is the amount you have to pay to Dope?
Input
T number of test cases. Each case consists of two lines. first line N number of white balls. Next line contains a b c use to generate N mass using:
mass = (a * i + b) % c; for 1 <= i <= N
Output
A single line for each case containing the amount you need to pay.
Constraints
1 <= T < 1000
1 <= N < 10000
1 <= a, c < 1000
0 <= b < 1000
Example
Input:
2
3
1 0 10
4
2 1 10
Output:
2
10
Explanation
Case 1: 3 mass = 1 2 3; output = 2
Case 2: 4 mass = 3 5 7 9; output = 10 | 32,254 |
GLJIVE (GLJIVE)
In front of Super Mario there are
10 mushrooms
, arranged in a row. A certain amount of points is awarded for picking each of the mushrooms. Super Mario must pick mushrooms
in order
they appear, but is not required to pick them all – his goal is to score a number of points
as close as possible to 100
.
In case there exist two such numbers which are equally close to 100 (e.g. 98 and 102), Mario will pick the
greater
one (in this case 102).
Help Super Mario and tell him how many points he will score.
Input
Input consists of 10 lines, each of which contains one positive integer less than or equal to 100, denoting the scores awarded for picking each mushroom, in the order that Mario can pick them in.
Output
The first and only line of output must contain the required number of points.
Example
Input:
10
20
30
40
50
60
70
80
90
100
Output:
100 | 32,255 |
Spreadsheet scrolling (SCROLL)
Sruthi is looking at a spreadsheet containing N rows. Only K rows of the spreadsheet are visible at a time (If the top row is i, the bottom row will be i+K-1). In the beginning, rows 1 ... K are visible. Sruthi needs to read certain values from rows r1, r2 ... rM in that order. It is possible to scroll the spreadsheet so that the rows j ... j+K-1 can be viewed instead of the current i ... i+K-1. This operation counts as one scroll and its scroll length is defined as |j-i|
Find the minimum number of scrolls required so that Sruthi can read of all the M values in the given order. As there may be more than one way to do this, also find the minimum total scroll length required to do the reading in so many scrolls.
Input
The first line of the input contains the integer T (≤ 20), the number of test cases to follow.
The description of each test case begins with a line containing 3 integers N (≤ 10
8
), K (≤ 10
8
) and M (≤ 50000) as defined in the problem. Following this are M lines giving the row numbers from which values have to be read sequentially.
Output
Output two space separated integers in a line per test case : The minimum number of scrolls required and the minimum scroll length required for the minimum number of scrolls.
Example
Input:
2
20 10 2
10
20
20 10 2
10
7
Output:
1 10
0 0 | 32,256 |
Chocolate distribution (CHOCDIST)
In Dystopia, chocolates are being distributed to children waiting in a queue. The distribution proceeds as follows. Each chocolate bar is rectangular in shape with integer edge lengths. If the chocolate bar is a square, it is given away completely to the first child in the queue. Otherwise the largest possible square piece of chocolate is broken off from the chocolate bar and given to the first child. After a child receives his share of chocolate, he leaves the queue. The remaining portion of the chocolate bar is dealt with in the same fashion and the whole or a portion of it is given to the next child in the queue.
For example, if we start with a 5×3 chocolate bar, the first child in the queue receives a 3×3 chocolate bar, leaving a 2×3 bar. The second child gets a 2×2 bar while the third and fourth children get 1×1 bars. Thus four children have been fed using the 5×3 bar.
The Dystopian government has got a carton of chocolate bars to be distributed to children in the country. To make sure that maximum inequality is achieved while distributing chocolates, the chocolate bars in the carton are all of different sizes. For every i such that M ≤ i ≤ N and every j such that P ≤ j ≤ Q (where M,N,P,Q are integers) there is exactly one chocolate bar of length i and breadth j in the carton. Here a bar of length i and breadth j is considered to be different from a bar of length j and breadth i.
Given the values of M,N,P,Q find the number of children that can be fed with the chocolate in the carton.
Input
The first line of the input contains the number of test cases, T (≤ 1000)
Following this are T lines, each describing a test case with four integers M,N,P,Q separated by spaces (1 ≤ M ≤ N ≤ 100000000, 1 ≤ P ≤ Q ≤ 1000)
Output
Output T lines, each containing an integer : The number of children that can be fed using the chocolate in the carton
Example
Input:
2
1 2 1 2
3 4 4 5
Output:
6
14 | 32,257 |
Triangle equality (TRIEQUAL)
Consider three distinct points A,B,C on a plane. The sum of straight line distances from A to B and B to C is always greater than or equal to the straight line distance from A to C. Equality holds only when ABC is a degenerate triangle. This is the famous
triangle inequality
.
In this case, distance between points is measured by the Euclidean metric, i.e. the distance between points (x
1
, y
1
) and (x
2
, y
2
) is given by sqrt((x
1
- x
2
)
2
+ (y
1
- y
2
)
2
). However, this is not the only metric possible. Another common metric used is the
Manhattan metric
where the distance between the pair of points is given by |x
1
- x
2
| + |y
1
- y
2
|.
You are given N distinct points on a plane where distances are measured using the Manhattan metric. Find the number of ordered triplets of distinct points (A, B, C) such that the sum of distances from A to B and B to C is equal to the distance from A to C.
Input
The first line of input contains an integer T (≤ 10), the number of test cases to follow.
Following this are the descriptions of T test cases. Each test case description begins with an integer N (≤ 50000), the number of points. Following this are N lines, each giving the x and y coordinates of a point (0 ≤ x
i
, y
i
≤ 10
8
) separated by a space.
Output
Output T lines, each containing the number of ordered triplets of distinct points in every test case with the given property
Example
Input:
2
3
0 0
1 1
2 2
3
0 0
1 2
2 1
Output:
2
0 | 32,258 |
Military patrol (MILPATR)
Dystopia consists of N cities. There are one-way roads connecting some pairs of cities. The dysfunctional state has recently seen a lot of protests to overthrow the tyrannical ruler and the government plans to use military patrol vehicles to make sure that the protests are suppressed. Every patrol vehicle is assigned a sequence of cities. If a patrol vehicle is assigned the cities c
1
, c
2
... c
k
then it starts from the city c
1
and takes the direct one-way road to c
2
, from there it takes the one-way road to c
3
and so on. Finally the vehicle takes the one way road from c
k
to c
1
. This routine is repeated everyday to keep the protestors perpetually under fear.
Now note that:
Every city has to appear in exactly one vehicle's patrol sequence exactly once
Every patrol vehicle has to move - so it has to be assigned more than one city
The government does not have any limit on the number of patrol vehicles it can use. However, they want to make sure that the least possible amount of money is spent on the patrol mission and hence they want to minimise the total distance travelled by the patrol vehicles.
Given the road network of Dystopia, find the minimum total distance the patrol vehicles need to move so that all the cities can be patrolled. If it is impossible to organise a nationwide patrol with the given constraints, report the same.
Input
First line of the contains T, the number of test cases (T ≤ 10)
This is followed by the descriptions of the T test cases. The first line of the description contains two integers N and R, the number of cities and one way roads respectively (N ≤ 200, R ≤ 10000). The cities are numbered 1, 2, 3 ... N This is followed by R lines, each representing a one way road by 3 integers N
1
, N
2
and D : the start city, the end city and the length of the road respectively (N
1
≠ N
2
, 1 ≤ D ≤ 1000000). You are assured that there is no more than one one way road from any N
1
to N
2
Output
For each test case output one line. If the patrol can be done, output the minimum total distance that the patrol vehicles have to travel. Otherwise output Impossible
Example
Input:
2
3 3
1 2 1
2 3 1
1 3 1
4 6
1 2 2
2 3 2
3 4 2
4 1 2
1 4 1
3 2 1
Output:
Impossible
6 | 32,259 |
Partitioning the plane (PARTPLNE)
You are given the coordinates of 4×K+5 points on a plane such that no three of them are collinear. You need to select five points from these : a central point O and four arm points A, B, C, D such that:
Rays from the centre to the arm points divide the plane into four regions containing an equal number of points.
None of the four central angles is a reflex angle.
Sum of absolute values of the cotangents of the central angles is as low as possible.
If it is possible to choose points satisfying this condition, output the lowest possible value for the sum of absolute values of the cotangents of the central angles. Otherwise report that it is not possible.
Input
The first line of input contains T (≤ 4), the number of test cases. Following this are the descriptions of the T test cases.
The first line in the description of each test case gives K (≤ 100). Following this are 4×K+5 lines giving the x and y coordinates of each point separated by a space (0 ≤ x, y ≤ 10
6
)
Output
For each test case output in a different line the minimum sum of absolute values of the cotangents of the central angles, with six digits after the decimal point. If the division cannot be done in the manner explained, print Impossible.
Example
Input:
2
0
0 0
0 1
1 1
1 0
2 3
0
0 0
2 0
0 1
2 1
1 2
Output:
4.500000
Impossible | 32,260 |
Leaky containers (LEAKCONT)
The acid manufacturing company has a special room to store leaky acid containers. The container holders in the room, which have the capacity to hold one leaky container each, are arranged in a rectangular grid of R rows and C columns such that the columns are in the North-South direction while the rows are in the East-West direction. Currently there are N leaky containers in some of the holders and M more have just arrived and need to be placed in the holders.
The company has realised that the containers being produced these days are exceptionally leaky. So much so that the acid that is leaking is corroding the holders completely.
Every acid container leaks either in the North-South direction or the East-West direction. Containers can be rotated by 90 degrees and thus a container that is leaking in the East-West direction can be made to leak North-South and vice versa. Given enough time, a leaky container can corrode the holder completely and start corroding the two adjacent holders in the leak direction and this process can go on.
The company employee has to make a decision fast. He needs to rotate some of the existing containers and place the new containers in proper holders and directions such that the total number of holders that will be corroded is minimised.
Find out the minimum number of holders that will be corroded after proper placement of the new containers and proper orientation of all containers.
Input
The first line of the input contains the number of test cases T (<=10).
For each test case, the first line has four numbers R, C, N and M (1<=R,C<=100, 1<=M,N<=20, M+N<=R*C). This is followed by N lines, each giving the location and leak direction of an existing container by 3 integers r (row number), c (column number) and d (1 if leakage is N-S, 0 if E-W). Numbering of rows and columns begins with 1.
Output
For each test case, output on a different line the smallest number of holders that will get corroded after rotating the existing containers and placing the newly arrived containers.
Example
Input:
2
4 6 4 4
1 2 0
2 4 0
3 2 1
3 5 1
50 50 5 10
1 35 1
17 44 0
17 46 1
42 35 1
42 46 0
Output:
12
148 | 32,261 |
Progressive progressions (PROGPROG)
An arithmetic progression is a sequence of numbers a
1
, a
2
... a
n
such that a
i+1
-a
i
is equal for all 0 ≤ i < n. This difference is called the common difference of the arithmetic progression.
Now consider a sequence of arithmetic progressions A
1
= (a
1,1
, a
1,2
... a
1,n
1
), A
2
= (a
2,1
, a
2,2
... a
2,n
2
) ... A
k
= (a
k,1
, a
k,2
... a
k,n
k
)
A progressive progression is such a sequence with the additional properties that:
a
i,n
i
= a
i+1,1
for 1 ≤ i < k
c
i
, the common difference of A
i
, is a positive factor of a
i,1
for 1 ≤ i ≤ k
c
i
i+1
for 1 ≤ i < k
n
i
> 1 for 1 ≤ i ≤ k
k ≥ 1
Find the number of progressive progressions such that a
1,1
=1 and a
k,n
k
= N. As this number can be quite large, output it modulo 100000007.
Input
The first line of input contains T (≤ 100), the number of test cases. This is followed by the description of the test cases. The description of each test case consists of a single integer N (1 < N ≤ 1000000).
Output
For each test case, output modulo 100000007 the number of progressive progressions such that a
1,1
=1 and a
k,n
k
= N
Example
Input:
2
5
10
Output:
1
6 | 32,262 |
Move the books (MOVEBOOK)
Sheldon and Lenard are a pair of nerds playing an unimaginatively named game, "Move the books". The game board is an infinitely long strip of cells numbered 1,2,3.... from left to right. On certain cells, their favourite physics books have been placed. A player's move consists of taking any one of the books and moving it to any cell which lies to its left. But there is a constraint that you are not allowed to make your book jump over a cell that contains a book already (ie, You cannot move a book from cell j to cell i < j if there is a cell k which contains one or more books such that i < k < j). However, you can place a book into a cell even if it contains one or more books already. But books that are placed in a cell are stacked in the order in which they arrive and hence only the topmost book (the last arrived one) can be moved from there. The players make moves alternately, and the person unable to move any book loses.
They have been playing the game for a long time. Sheldon makes the first move in all the games and wins most of the time. Lenard is fed up and wants to make the first move. However, Sheldon doesn't yield and this leads to an argument. This is the final agreement they have come up with:
They start with N books placed in different cells. The arrangement is computer generated and hence there is no player role in this step
Lenard picks two natural numbers a & c while Sheldon picks a natural number b. Both are unaware of the number(s) the other person has chosen while choosing their own number(s). Three more books are now added to the set : a cells to the right of the rightmost current book, b cells to the right of this book and c cells to the right of the latter book.
They start the game with the same rules as earlier, with Sheldon making the first move.
Now Lenard feels that there might be certain pairs (a,c) such that independent of which number Sheldon chooses, Lenard is assured to win the game. Given the initial configuration of the board find all such pairs, sort them lexicographically [(a
1
,c
1
) < (a
2
,c
2
) iff a
1
< a
2
or (a
1
=a
2
and c
1
< c
2
)] and output the Kth such pair. If there are less than K pairs with this property, output Impossible
Input
The first line of the Input contains T (≤50), the number of test cases. Following this are the descriptions of the T test cases
The first line in the description of each test case contains two space separated integers N (≤1000) and K (≤10
8
). Following these are N lines, each containing the location of a book. The book positions are given in increasing order and will each fit in a 32 bit signed integer.
Output
For each test case output the Kth lexicographically smallest pair of integers that will assure Lenard a win. The two integers should be separated by a space and pairs for each test case should be output on a new line. If for any test case there are less than K pairs of integers that assure Lenard a win, on the line for that test case output Impossible
Example
Input:
1
1 1
1
Output:
1 1 | 32,263 |
Road trip (ROADTRIP)
Phileas Fogg and Passepartout are now going on a road trip in their brand new car. They start at location A
0
and need to go to A
N
. Their car has a capacity to hold only C units of fuel and can travel unit distance on unit amount of fuel. They start by filling some amount of fuel from the filling station at A
0
. On the way, there are several filling stations A
1
, A
2
,... A
N-1
. The cost of fuel is not the same at all filling stations. Find the minimum amount that they have to spend on fuel to make the journey. Note that it is assured that the journey can be completed with the car of the given capacity.
Input
The first line of input contains T (≤ 10), the number of test cases. Following this are the descriptions of the test cases.
The first line in the description of each test case contains two space integers N (≤ 50000) and C (≤ 10
8
). This is followed by N lines, each containing an integer. The integer on the ith line is the distance from A
0
to A
i
and is ≤ 10
8
. The distances are in increasing order. This is followed by N more lines, each containing an integer. The integer on the ith line is the cost of one unit of fuel at the filling station A
i-1
and is ≤ 10
8
.
Output
Output one integer per test case, the minimum total amount that needs to be spent on fuel to complete the journey.
Example
Input:
2
5 10
10
20
30
40
50
1
2
1
2
1
5 15
10
20
30
40
50
1
2
1
2
1
Output:
70
60 | 32,264 |
Giant fountain (GNTFNTN)
The Dystopian government has installed a giant fountain in front of the parliament building. The fountain consists of N levels stacked one on top of the other and is situated on top of a large tank of infinite capacity. The levels of the fountain are numbered 1 to N from top to bottom. The top l
1
levels are identical with capacity c
1
, the next l
2
levels identical with capacity c
2
... the final l
K
levels with capacity c
K
. Here l
1
+ l
2
+ ... l
K
= N.
When water is added to level i beyond its capacity, the excess water overflows to level i+1. Water overflowing from level N is collected in the tank. Water is added to the levels in the following fashion. First, w
1
amount of water is added to each level i such that s
1
≤ i ≤ e
1
. Then w
2
amount of water is added to each s
2
≤ i ≤ e
2
... Finally w
M
amount is added to s
M
≤ i ≤ e
M
. Note that water might be added to the same level multiple times in this fashion. You have to find out the amount of water that has overflowed to the tank at the bottom, and the total number of levels of the fountain that are completely filled
Input
The first line of the input contains T (≤ 10), the number of test cases. Following this are the descriptions of the test cases.
The first line of the description of a test case contains space separated integers N (≤ 2 × 10
8
), K (≤ 2000) and M (≤ 10
4
). Following this are K lines, each containing a space separated pair of integers. These are the (l
i
, c
i
) pair as explained in the problem statement. Here l
1
+ l
2
+ ... l
K
= N and c
i
≤ 10
8
. This is followed by M lines, each containing a space separated triplet of integers. These are (s
i
, e
i
, w
i
) as explained in the problem statement. 1 ≤ s
i
≤ e
i
≤ N and w
i
≤ 10
6
Output
For each test case output a space separated pair of integers : The total amount of water that has overflowed to the tank and the number of levels of the fountain that are completely filled.
Example
Input:
1
10 2 1
5 6
5 3
3 9 5
Output:
5 5 | 32,265 |
Sister cities (SSTRCITS)
Unlike Dystopia, the neighbouring nation of Utopia believes in economic development. To improve the economy of the nation, the Utopian government has decided to select some pairs of cities as sister cities and take steps to improve trade relations between each pair.
There are N cities in Utopia, numbered 1 to N. There are two-way roads connecting some pairs of cities. The total number of roads in Utopia is R. Now the road network in Utopia has been created efficiently so that there is no road that is redundant. That is, there is exactly one way to travel between any pair of cities without using the same road twice. Now when a pair of cities is chosen as sister cities, the government wants to make sure that there is a direct road between them. Also, a given city cannot have more than one sister.
Given the road network of Utopia, find the number of ways of selecting K pairs of sister cities under these constraints. As the answer can be quite large, output it modulo 100000007.
For example, assume that there are 6 cities in Utopia. There are direct roads between the following pairs of cities : (1, 2), (2, 3), (2, 4), (4, 5), (4, 6). Notice that there is exactly one way to travel between any pair of cities. If the government wants to select two pairs of sister cities, it can do it in four ways : {(1, 2), (4, 5)}, {(3, 2), (4, 5)}, {(1, 2), (4, 6)}, {(3, 2), (4, 6)}
Input
First line of the input contains T (≤10), the number of test cases. This is followed by the description of the test cases.
The description of each test case begins with a line containing 3 space separated integers N (< 400), R (< 10000) and K (< 400). Following these are R lines, each representing a road in Utopia. The line will contain two different space separated integers N
1
and N
2
implying that there is a two way road between N
1
and N
2
. You are assured that the road network has the property as described in the problem statement.
Output
For each test case, output modulo 100000007 the number of ways of selecting K pairs of sister cities satisfying the conditions in the problem statement.
Example
Input:
2
3 2 1
1 2
2 3
6 5 2
1 2
2 3
2 4
4 5
4 6
Output:
2
4 | 32,266 |
Ski slopes (SKISLOPE)
A skier wants to ski down from the top of a mountain to its base. There are several possible routes, using different slopes enroute, and passing through some flat areas. The effort expended in skiing down a slope depends upon the length of the slope and the speed of skiing. For each slope, there is a maximum advisable speed. The skier wants to use a route that minimizes the
average effort spent per unit distance traveled
(i.e. the total effort expended divided by the total distance traveled).
The flat regions on the mountain are numbered 1 to N from top to bottom. The skier begins at level 1 and needs to reach level N. You are given the numbers of the flat regions each slope connects. Note that on a slope, one can only ski downwards. For each slope, you are also given the length of the slope and the maximum advisable speed for it. The effort expended in skiing down a particular slope is given by the following formula:
e = d × (70 - s) if s ≤ 60, and e = d × (s - 50) if s > 60
where e is the effort required, d is the distance traveled and s is the speed of travel.
You have to determine the minimum average effort per unit distance that the skier has to expend in order to reach the mountain base, while staying within the maximum advisable speed at every slope.
Input
The first line of input gives the number of test cases T (≤ 20). This is followed by the descriptions of the test cases
For each test case, the first line of input gives the number of flats, N (N ≤ 1000), and the number of slopes, R (R ≤ 20000), connecting them respectively. Each of the next R lines describes a slope by giving: the numbers of the flats at the top and the bottom of the slope, the maximum advisable speed for the slope (≤ 100), and the length of the slope (≤ 1000) respectively.
Output
For each test case, output a single number (with four places after the decimal point, rounded up) that gives the minimum average effort per unit distance that needs to be expended to ski down from the mountain top to the base. The output for each test case should be on a separate line.
Example
Input:
2
4 5
1 4 30 60
1 2 50 40
1 3 60 20
2 4 60 50
3 4 50 50
3 3
1 2 50 40
1 3 40 20
2 3 20 30
Output:
14.4445
30.0000 | 32,267 |
Place-name game (PLCNMGME)
Place-name game is a favourite pastime among the few children that go to school in Dystopia. The game is played as follows : One player says the name of a city and the next player has to say the name of a city that begins with the last letter of the said city. The game then goes on.
Dystopian cities recently went through a massive renaming. Now each city has a name that begins with a consonant and ends with a consonant.
Anaximander is a student with a very poor knowledge of geography. Hence he fares very poorly in the game. He has recently come up with a new idea. He would just remember the name of 21 Dystopian cities. He wants to choose the 21 cities such that there is exactly one city name starting with each consonant and exactly one city name ending with each. This would give him a good advantage in the game, whether he is playing first or second.
Given the names of the N cities in Dystopia, find out the number of ways Anaximander can select 21 city names out of the lot satisfying the properties. As this number can be very large, output it modulo 100000007.
Input
The first line of the input contains N (≤1000), the number of cities. This is followed by N lines, each containing the name of a city in Dystopia. Each city name will begin and end with a consonant, and will contain at least 2 and at most 10 letters.
Output
Output modulo 100000007 the number of ways Anaximander can choose 21 city names out of the N with the intended properties.
Example
Input:
23
BBBB
CCCC
DDDD
FFFF
GGGG
HHHH
JJJJ
KKKK
LLLL
MMMM
NNNN
PPPP
QQQQ
RRRR
SSSS
TTTT
VVVV
WWWW
XXXX
YYYY
ZZZZ
BAAC
CAAB
Output:
2 | 32,268 |
Enumeration of rationals (ENUMRTNL)
It is well known that rational numbers form a countable set. Hence the set of rational numbers in the open interval (0,1) also form a countable set.
Here we enumerate the rationals in (0,1) in the following fashion. First, every rational is expressed in the lowest terms : ie, as p/q where p and q are positive integers with no common factor other than one. Then we sort the fractions in the ascending order of p+q. In case of a tie, the smaller fraction comes first.
The first few terms in this enumeration are 1/2, 1/3, 1/4, 2/3, 1/5, 1/6, 2/5...
Given a natural number N, find the numerator and denominator of the Nth term in the enumeration.
Input
The first line of the input contains T (≤ 1000), the number of test cases. This is followed by T lines, each containing an integer N (≤ 10
11
).
Output
For each value of N, output separated by space the numerator and denominator (in lowest terms) of the Nth fraction in the enumeration
Example
Input:
2
3
6
Output:
1 4
1 6 | 32,269 |
Counting the teams (CNTTEAMS)
The teacher in the Dystopian School for Politics and other Dirty Games (DSPDG) is training students in group activities. She feels that to really understand group behavior, students need to practice working in groups of different sizes. This is how she groups the students:
There are N students in the class, with roll numbers from 1 to N(2≤N≤10
12
). The teacher generates using her laptop a random permutation of the roll numbers. The student with the roll number equal to the i
th
number in the permutation is assigned as a "target" to the student with roll number as i (Note that "targetship" is not mutual. If 1 is the target for 2, 2 need not be the target for 1). If any student is assigned himself as the target, the teacher generates another permutation till no student is assigned himself.
The N students stand far from each other. Now student 1 goes and joins his target. After this, student 2 (and any student who is with him) joins 2's target. At the i
th
step, student i and anyone who is already with him joins i's target. In case i's target is already with him, nothing is done.
By following this procedure, when all students have joined their targets, the class gets split into some groups. For example, assume that there are 6 students in the class and the permutation that has been generated is {2,4,5,6,3,1}. First, 1 goes and joins 2. Then 1 and 2 join 4. Then 3 joins 5. Then 1, 2 and 4 join 6. 5 is already with 3 and hence does not move. Similarly 6 is already with 1 and does not move. In the end, we have 2 teams : {1,2,4,6} and {3,5}
Given N, find out the expectation value of the number of teams that will be formed when the teacher groups the class in this fashion.
Input
First line of the input contains T (≤100), the number of test cases. Following this are T lines, each containing an integer N (2≤N≤10
12
).
Output
For each N, output the expectation value of the number of groups formed. Output 6 digits after the decimal point while printing the expectation value
Example
Input:
2
3
4
Output:
1.000000
1.333333 | 32,270 |
BRODOVI (BRODOVI)
Mirko lives in a small town with a harbour: once in a blue moon a ship passes by. However, to this day Mirko remembers the day when all the ships who had ever visited the harbour showed up. He denoted this day by index 1. Many days have passed since, but Mirko noted each day when at least one ship visited the harbour, naming these days entertaining. Additionally, Mirko has noticed that each ship visits the harbour periodically, at regular intervals. For instance, an interval of length 3 implies that some ship visited the harbour on days 1, 4, 7, 10 etc.
Given Mirko’s list of entertaining days (including today which is considered to be an entertaining day as well), compute the minimum possible number of ships visiting his harbour.
Notes: All entertaining days appear on Mirko’s list. It is guaranteed that the given data is consistent - in other words, a solution will always exist.
Input
The first line of input contains an integer N (2 ≤ N ≤ 5000), the number of entertaining days. The following N lines contain indices of entertaining days, one per line, in ascending order. The first and the last indices, representing the day from which Mirko started monitoring harbour traffic and today, respectively, will always appear on the list. The first index will always be 1, and the last one (index of today) will be less than 10
9
.
Output
The first and only line of output must contain the required minimum number of ships.
Example
Input:
5
1
7
10
13
19
Output:
2 | 32,271 |
KOSARK (MIDO)
Slavko has started to follow the NBA league. The game duration is exactly 48 minutes. When a game ends, the statistics are shown. Slavko has written down whenever a team scored. He is curious about how long each team was in the lead.
Input
The first line of input contains one integer N (1 ≤ N ≤ 100). The following N lines describe events when a team scored. Each description consists of a team that scored, which is either 1 or 2, and a timestamp in format MM:SS (minutes:seconds), the time when a team scored. Minutes and seconds are zero padded and from ranges [00, 47] and [00, 59] (inclusive). The given timestamps are unique.
Output
The first line of output must contain the duration that the first team was in the lead.
The second line of output must contain the duration that the second team was in the lead.
All durations should be in MM:SS format, with leading zeros.
Sample
Input
3
1 01:10
2 21:10
2 31:30
Output
20:00
16:30 | 32,272 |
COSTLY CHESS (CCHESS)
In the country of Rome, Chess is a royal game. For every move the players had to give some bucks to the Emperor Jurg. The LGMs or Little Green Men, are very good player of chess. But as chess is an expensive game, that's why it is royal, they asked you to help them find the minimum bucks which they had to pay for moving their knight from one position to another. Any number of steps can be used to reach the destination.
Constraints
The chess has a dimension of 8×8, and the index of left bottom cell (0, 0).
Knight move only in a standard way, i.e. 2 row and 1 column or 1 row and 2 column.
If in a step knight move from (a, b) to (c, d), then LGM had to pay a×c + b×d bucks to Emperor Jurg.
0 ≤ a, b, c, d ≤ 7
Input
There are 100-150 test cases. Each test case is composed of four space separated integers. The first two numbers, a, b, are the starting position of the knight and the next two, c, d, are the destination of the knight. Read up to End Of File.
Output
For each test case, print the minimum amount of bucks they had to pay in separate line. If it's impossible to reach the destination then print -1.
Example
Input:
2 5 5 2
4 7 3 2
1 2 3 4
Output:
42
78
18
Explanation for Test Case 1
For moving knight from (2, 5) to (5, 2) in minimum cost, one of the path is (2, 5) → (3, 3) → (5, 2)
Bucks paid:
(2, 5) → (3, 3) = (2 × 3 + 5 × 3) = 21
(3, 3) → (5, 2) = (3 × 5 + 3 × 2) = 21
Total cost = 42
To infinity and beyond... | 32,273 |
TRIANGULAR PRISM (PRISMSA)
In a far away nation, all the liquid substance are stored in a can of shape of a triangular prism. According to belief, this will bring security to their children. As they are very resource conservative people, unlike the earth natives, they want to use as less as possible amount of the raw material to be used for producing the can, which directly depends on the surface area of the can. Mr. Buzz Light Year, of Star Command, is provided with the responsiblity to find the minimal suface area required to prodce a can of a given volume.
Notes:
Consider the material the can is made of to be infinitely thin.
The base of the prism is equilateral triangle.
Some formulas:
a: triangle side's length.
h: height of the prism.
Volume, V = (a
2
* sin(60°) * h)/2
Surface Area, S = a
2
*sin(60°) + 3*a*h
If not provided by a library, use the alue of 2*acos(0) for PI(π).
Reminder:
If your result is
within 10
-2
of the expected result, your solution will be evaluated as correct.
If your result is
between (1-10
-2
)*expected and (1+10
-2
)*expected
, it will be evaluated as correct.
Constraints
Given volume will be an integer between 1 and 100000, inclusive.
Input
Input begins with a integer t, number of test cases. Then follows t lines, each one containing an integer, V, given volume.
Output
For each volume, print the minimum surface area required to produce the can in separate line.
Example
Input:
5
10
5
100
245
5421
Output:
30.3872837089
19.1427891970
141.0452767471
256.3318686611
2020.2796324002
Explanation for test case 1:
Volume = 10, a = 3.41995, h = 1.97451, Minimum Surface Area = 30.3872837089 | 32,274 |
Triple Sums (TSUM)
You're given a sequence
s
of
N
distinct integers.
Consider all the possible sums of three integers from the sequence at three different indices.
For each obtainable sum output the number of different triples of indices that generate it.
Constraints:
N ≤ 40000, |s
i
| ≤ 20000
Input
The first line of input contains a single integer N.
Each of the next N lines contain an element of s.
Output
Print the solution for each possible sum in the following format:
sum_value : number_of_triples
Smaller sum values should be printed first.
Example
Input:
5
-1
2
3
0
5
Output:
1 : 1
2 : 1
4 : 2
5 : 1
6 : 1
7 : 2
8 : 1
10 : 1
Explanation:
4 can be obtained using triples ( 0, 1, 2 ) and ( 0, 3, 4 ).
7 can be obtained using triples ( 0, 2, 4 ) and ( 1, 3, 4 ).
Note:
a triple is considered the same as any of its permutations. | 32,275 |
PARKET (PARKET1)
Ivica has set up a new parquet flooring in his room. The room is L decimeters long and W decimeters wide.
The blocks are of quadratic shape and each has an area of one quadratic decimeter. Once Ivica had set up the flooring, which consists of brown blocks, he decided to paint the blocks on the edge of the room red.
The picture below illustrates the scenario from the test case #2 – outer blocks are red, while the remaining two inner blocks are brown:
Marica has come to visit Ivica. While Ivica was serving her cookies, she counted the number of blocks of each color. When she returned home, she recalled of the two numbers and wished to calculate the dimensions of Ivica’s room. Help her!
Input
The first and only line of input contains two integers separated by a space, R (the number of red blocks) and B (the number of brown blocks). The following constraints will apply: 8 ≤ R ≤ 5000, 1 ≤ B ≤ 2×10
6
.
Output
The first and only line of output must contain the dimensions of the room, L and W, respectively. If the numbers differ, output the greater one first. The test data will ensure that a unique solution always exists.
input 1:
8 1
output 1:
3 3
input 2:
10 2
output 2:
4 3 | 32,276 |
The Ball (BALL)
In a coordinate plane, there are N horizontal conveyor belts, each moving either leftwards or rightwards. When the ball falls on a belt, the belt drags it in direction it's moving. When the ball reaches the end of the belt, it falls vertically downwards. For example, if the belt is moving rightwards and it ends in the unit square with x-coordinate 12, the ball will fall from the belt on the x-coordinate 13, and continue falling on the same x-coordinate until it falls on another belt or reaches the ground (the height of 0).
Frane drops a ball many times (from the height that is greater than any of the belt heights), from various x-coordinates, and your task is: for each ball Frane drops, determine the direction of each belt such that this ball falls on as many belts as possible.
This picture represents the first test example:
Input
In the first line of input, there is an integer N (the number of conveyor belts, 1 ≤ N ≤ 100000).
In each of the next N lines, there are integers X1, X2, Y (X1 ≤ X2, 0 < X1, X2, Y < 10
9
) representing the belt. Imagine the belt as a segment of which the bounding unit squares are (X1, Y) and (X2, Y). The belt's thickness is zero and it lies on the bottom of the given unit squares. The belts will not touch or overlap each other.
In the next line, there is an integer Q (the number of falling balls, 1 ≤ Q ≤ 100000).
In the next Q lines there is an integer less than 10
9
, representing the x-coordinate of the unit square Frane drops the ball from.
Output
For each of the Q queries, output the greatest possible number of the conveyor belts visited by the ball.
Example
Input:
3
1 4 3
5 7 2
2 4 1
4
1
4
5
6
Output:
3
3
2
2
Input:
3
5 20 20
15 30 15
10 14 11
3
5
30
516546
Output:
3
2
0 | 32,277 |
Youtube (YOUTUBE)
N students are bored in computer class so they watch funny video clips on YouTube.
The site contains K popular clips, numbered 1 through K. When a video clip is watched, a list of similar video clips is displayed on the side.
Every student picks a video clip from the main page and starts watching it. After exactly one minute every student gets bored of his or her video clip, so he opens the
first
video clip from the list of similar clips on the side (even if he already watched that clip).
Write a program that determines for each student which video clip he will be watching
during the M-th minute
of the class.
Input
The first line contains three integers N, K and M (1 ≤ N, K ≤ 100 000, 1 < M ≤ 1 000 000 000), the numbers of students, video clips and minutes.
The second line contains N integers, each between 1 and K, the indices of video clips the students start watching.
The third line contains K integers, each between 1 and K, the index of the first similar clip for each video clip.
Output
Output N integers, the indices of video clips that students will be watching during the M-th minute.
Example
Input:
4 5 2
1 2 4 3
5 5 1 2 3
Output:
5 5 2 1
Input:
2 6 5
1 6
2 3 4 1 4 5
Output:
1 2 | 32,278 |
Quadratic Equation (QUADRATE)
Manohar is new to mathematics and now a days he is learning quadratic equations. He is learning that how to find for a given quadratic equation that whether equation has equal roots, imaginary roots or real but distinct roots. His teacher has given him some quadratic equations and told him to tell the nature of roots. Manohar is not sure for his solutions so he want your help. Write a program that determine the nature of roots.
Input
In the first line number of test cases is given (T <= 10). Then T lines follows each containing a quadratic equation in the form a*x*x + b*x + c = 0, where a, b, c are constants 0 < a < 1000 and -10000 <= b, c <= 10000.
Output
For each test case output "Equal roots.", "Imaginary roots." or "Distinct real roots." according to nature of the roots as explained above.
Example
Input:
2
x*x-2*x+1=0
2*x*x+5*x-3=0
Output:
Equal roots.
Distinct real roots. | 32,279 |
Temple Queues (TEMPLEQ)
The
Tirumala temple
is the most visited place of worship in the world. As the number of pilgrims who visit the temple each day is very high, the head of the temple should keep monitoring the queue system. Today is another lovely day and he has started his work. There are
N
queues at the entrance of the temple and some of them are already filled with pilgrims. Each queue has a metal door at the beginning, which leads to the temple. When the door is opened, it allows only one pilgrim to get through it and it gets closed immediately after that.
New pilgrims are rushing in to the queues and the head needs to monitor the current sizes of the queues and decide which doors to be opened. At any time, he wants to know how many queues currently have at least
X
pilgrims. He also decides an integer
Y
and wants to open the doors of all the queues having at least
Y
pilgrims at that time. You are the controller of the queue system and are following his instructions. Respond quickly and win yourself a big laddu (sweet) from him :) .
Read the input section for rest of the details.
Input
The first line contains two integers N and Q. N - The number of queues [1 <= N <= 100,000], Q - The number of queries [0 <= Q <= 500,000]. The second line contains N integers, which are the initial sizes of the queues. ith integer (1-based) is the initial size of queue i [0 <= initial size <= 100,000,000]
Each of the next Q lines is one of the following:
1 A [One pilgrim enters the queue# A (1 <= A <= N)]
2 X [Find the number of queues having at least X pilgrims currently (0 <= X <= 1,000,000,000)]
3 Y [Open the doors of all the queues having at least Y pilgrims (1 <= Y <= 1,000,000,000), and thus allowing only one pilgrim to enter the temple from each of them]
Output
For each query of type "2 X" , print the answer in a new line.
Example
Input:
5 6
20 30 10 50 40
2 31
1 2
2 31
3 11
2 20
2 50
Output:
2
3
3
0
Note:
Ideal time limit should be 2s. It has been increased to 7s, to let Java solutions pass, as the I/O is huge. Edit: now 1s after server update.
There are multiple test sets, and the judge shows the
sum
of the time taken over all test sets of your submission, if accepted. | 32,280 |
Candies and Milestones (CANDYSTN)
Little Pratya loves collecting candies and she also likes playing games :).
Today Pratya is travelling in bus and she has a bag full of
N
candies. She looks outside the window and notices milestones with numbers written on them. She decides to play a game. She wants to select some initial
non-zero
number of candies from the bag and call it her collection of candies. When she sees a milestone on the way, she will add or remove some candies from her collection as following.
Let the previous milestone number be
a1
and the current milestone number be
a2
.
a2 > a1
: Pratya adds (a2 - a1) candies to her collection (thus, her bag of candies loses them). If the bag doesn't contain at least (a2 - a1) candies, she starts crying.
a2 < a1
: Pratya removes (a1 - a2) candies from her collection (thus, her bag of candies gains them). If her collection doesn't contain more than (a1 - a2) candies, she starts crying.
a1 = a2
: Pratya is bored to see the same number again and so she eats one of the candies from her collection.
Moreover, Pratya always wants her candy collection to have at least one candy, otherwise she starts crying. Given the numbers written on all the milestones in order, find the minimum number of candies Pratya should select in the beginning so that she doesn't have to cry at all. If it is not possible, print -1. Note that no change to the collection happens when she sees the first milestone.
Input
The first line contain the number of test cases
T
. Each test case has two lines. The first line specifies
N
and
M
.
N
is the number of candies in the bag and
M
is the total number of milestones. Second line contains
M
integers, the numbers written on the milestones, in the order Pratya sees them.
T ≤ 150
1 ≤ N ≤ 10
7
2 ≤ M ≤ 10
4
Each milestone number will be between [-10
6
, 10
6
].
Output
For each test case output the minimum number of candies that should be selected from the bag or -1 if its not possible.
Example
Input:
3
10 5
1 5 1 -1 -2
2 5
1 5 1 -1 -2
100 3
1 2 3
Output:
4
-1
1
Note : Large input, prefer using scanf / printf to cin / cout
* There are multiple test sets, and the judge shows the
sum
of the time taken over all test sets of your submission, if Accepted. | 32,281 |
Min Max 01 Path (MNMXPATH)
I have been asked to set a problem by SPOJ, what do I do now ? Lets see the standard stuff in most of the programming contests and make one problem out of it. Hmm... many problems are having Binary digits, Grids, Paths, Coins, Maximize or Minimize something, so let me mix them all now in to one problem, the one problem to rule them all ;)
Lets have a grid of size
N
x
M
having N rows and M columns, and put gold coins in it. How many in each cell ? , lets involve binary here. I'll give you two binary strings
A
[1...N] and
B
[1...M]. Cell (i, j) (1-based indexing) Row-i and Column-j in the grid contains A[i] * B[j] gold coins. From a cell (i, j), you can move to any of the 4 adjacent cells (i-1, j), (i+1, j), (i, j-1), (i, j+1) in one step. I want a path of
minimum length
from top-left cell (1, 1) to bottom-right cell (N, M), and the value of this path = number of gold coins it covers. Find the maximum value of such a path. Not every one wants to become a Raja, also find the minimum value of such a path.
Input
First line contains T [number of test cases, around 10 ]. T cases follow, each having 2 lines, "N A" and "M B" (quotes for clarity only). [1 ≤ N, M ≤ 100, 000 and each character in A, B is either 0 or 1].
Output
For each test case, print the maximum value of a path followed by the minimum value of a path, in the same line, separated by a single space. Output of each case should be in a separate line.
Example
Input:
2
4 1001
3 110
5 01111
3 110
Output:
3 1
5 0
Explanation
Case 1: A Maximum path in bold
11
0
0
0
0
0
0
0
1
10
Case 1: A Minimum path in bold
1
10
00
0
0
00
11
0 | 32,282 |
Favorite Sub Hair (FAVSUBS)
Little Princess Rapunzel is blessed with long (really looong!) hair, which is golden colored and has healing power. After the end of a long happy story, she marries her lover Flynn. They decide to lead a normal life by getting rid of the mysterious hair, which when cut loses its power and turns brown. There are many colorful beads on her hair in order. Rapunzel has some
K
favorite colors
B
[1...K]
To remember good old stories, she wants to keep a part of her hair after its cut. A favorite sub hair is that continuous part of the hair, which has each of her favorite color beads at least once.
For the purpose of this problem, we represent a color as an integer and Hair as an array
A
[1...N], which has exactly
N
colored beads in the given order. Could you please tell her the total number of ways she can cut her favorite sub hair (sub-array). Two sub-arrays are different, if their starting or ending index in A differ.
Input
First line contains T [ number of test cases, around 10 ]. Each test case is preceded by a blank line, including the 1st case. [ -2,000,000 <= A[i], B[j] ( colors ) <= 2,000,000 ]
Each test case has 4 lines, as described below.
N [ 1 <= N <= 100,000 ]
< Array A : N integers, separated by spaces >
K [ 1 <= K <= 1,000 ]
< Array B : K integers, separated by spaces, her favorite colors, without repetition >
Output
For each test case, output the number of different sub-arrays, which has her favorite color appearing at least once, in a separate line.
Example
Input:
3
4
1 2 3 1
2
1 2
6
10 20 30 40 50 60
1
20
5
1 2 3 4 5
2
2 6
Output:
4
10
0
Explanation:
Case 1 : Favorite sub-arrays in bold [
1 2
3 1 ], [
1 2 3
1 ], [ 1
2 3 1
], [
1 2 3 1
]
Note: Large input, prefer using scanf / printf to cin / cout
There are multiple test sets, and the judge shows the
sum
of the time taken over all test sets of your submission, if Accepted. | 32,283 |
Snaky Numbers (SNAKYNUM)
Sanky is a school kid and is very fond of numbers. His teacher gave his class a home work, asking each of them to invent a new series of numbers, with a large collection of numbers in them. His friend Evan has already invented one, which starts from 0 and picks every alternate number : {0, 2, 4 ,...} and he named them 'Evan' numbers :). Sanky is not happy because he couldn't invent that first and thinks picking every alternate number starting from 1 : {1, 3, 5, ... } would not be very odd ;).
After refreshing at home, he comes up with a new series of numbers in which the digits alternate between increasing and decreasing when compared with the digit before it, in a zig-zag fashion. To make it clear, if the number is abcde, either a < b > c < d > e or a > b < c > d < e. He cleverly named them 'Snaky Numbers' :). Eg: 8, 90, 243516 and 31524 are Snaky while 44, 123 and 4235 are not. He is now wondering if his Snaky series is large enough. Particularly, he wants to know how many 'Snaky Numbers' are there of length
at most
N
. Count only non-negative integers, without leading zeros.
The answer may get very big and not fit in Sanky's book, so please just tell him the ( answer modulo
M
)
Input
First line contains T [ number of test cases, around 50 ]. Each of the next T lines contains two integers N M.
1 <= N <= 1,000,000,000
2 <= M <= 1,000,000,007
Output
For each test case, output ( Number of Snaky numbers of length at most N ) % M, in a separate line
Example
Input:
3
1 101
2 107
3 1001
Output:
10
91
616
Hint:
You may have to use the mod operator wisely !
* There are multiple test sets, and the judge shows the
sum
of the time taken over all test sets of your submission, if Accepted. | 32,284 |
Revenge of the squares (SQUA_REV)
Given a number calculate the product N of their digits bigger than zero. The output is the number R of different (!) presentations of N in the form A×A+B×B with A and B being positive integers including zero.
Input
Twenty tests with one positive integer < 10
20
.
Output
Print the illustrated above number R for each test.
Example
Input:
5
7
78185824586267361855
Output:
1
0
3 | 32,285 |
Traversing Grid (BTCODE_A)
Given 2 points in 2 dimensional space (xs, ys) and (xd, yd), your task is to find whether (xd, yd) can be reached from (xs, ys) by making a sequence of zero or more operations.
From a given point (x, y), the operations possible are:
Move to point (y, x)
Move to point (x, -y)
Move to point (x + y, y)
Move to point (2 * x, y)
Input
The first line of input contains T, the number of test cases. T lines follow, one for each test case. For each test case, the input contains one line denoting the 4 integers xs, ys, xd, yd
Output
Output T lines, one for each test case. For each test case, output "YES" if (xd, yd) is reachable from (xs, ys) and "NO" otherwise. (quotes for clarity)
Example
Input:
1
1 1 2 2
Output:
YES
Constraints
T ≤ 25
-10
10
≤ xs, ys, xd, yd ≤ 10
10
Note that, although the input values are constrained by the above inequality, the coordinates of the points
at the intermediate steps need not be.
Explanation
Test case 1: We can move in the following manner: (1,1) → (2,1), using the operation (x, y) → (2 * x, y). Then, move from (2, 1) → (1, 2), using the operation (x, y) → (y, x). Finally use the operation (x, y) → (2 * x, y) to move from (1, 2) → (2, 2). | 32,286 |
Finding Minimum (BTCODE_B)
You are given 'n' integers k
1
, k
2
... k
n
and an integer 'x', which satisfy the equation x
1
k
1
* x
2
k
2
* ... * x
n
k
n
= x. You are also given values a
1
, a
2
... a
n
and y
1
, y
2
... y
n
. Your task is to find the least positive value 'v', that can be taken by the expression: a
1
*x
1
y
1
+ a
2
*x
2
y
2
+ ... + a
n
*x
n
y
n
. Note that x
1
, x
2
, x
3
... x
n
are some variables (not necessarily integers), which can only take positive values.
Input
The first line of input contains a single integer 't', denoting the number of test cases.
The first line of each testcase contains two space separated integers 'n' and 'x'.
Next line contains 'n' integers k
1
, k
2
... k
n
.
Next line contains 'n' integers a
1
, a
2
... a
n
.
Next line contains 'n' integers y
1
, y
2
... y
n
.
Output
For each testcase output the least positive value 'v' that can be taken by the expression. To avoid floating point errors, round it off to the nearest integer.
For example, 12.6 is rounded off to 13, and 12.4 is rounded off to 12. To avoid ambiguity, there will be no test case for which the fractional part of the answer equals 0.5.
Example
Input:
2
1 4
2
3
3
2 6
1 1
1 1
1 1
Output:
24
5
Constraints
t <= 25
1 <= n <= 20
1 <= x <= 1000000
1 <= k
i
, a
i
, y
i
<= 20
x
i
> 0
Explanation
Test case 1: x
1
2
= 4. Therefore, x
1
= 2 and 3*x
1
3
= 24.
Test case 2: x
1
*x
2
= 6. Minimum value of x
1
+ x
2
is 2*sqrt(6) = 4.89897. x
1
= sqrt(6) and x
2
= sqrt(6) gives this solution. Answer is 4.89897, which when rounded off to the nearest integer equals 5. | 32,287 |
Fun With Inequalities (BTCODE_C)
You are given 'n' inequalities. Each inequality is of one of the following 4 types:
Type 1: x > v
Type 2: x < v
Type 3: x = v
Type 4: x ≠ v
where 'x' is a variable which can only take non-negative integral values.
Your task is to find the maximum number of inequalities which are satisfied for some value of 'x'. You are also required to find the minimum value of 'x' for which the maximum number of inequalities are satisfied.
Input
The first line of input contains a single integer 'n', denoting the total number of inequalities. Each of the next 'n' lines contain 2 space separated integers t
i
and v
i
. t
i
denotes the type of inequality and v
i
denotes the value on the right hand side of the inequality.
Output
Output two space separated integers, the first integer denoting the maximum number of inequalities which are satisfied for some value of 'x', and the second integer denoting the minimum value of 'x' for which the maximum number of inequalities are satisfied.
Example
Input:
4
1 10
2 9
3 7
4 4
Output:
3 7
Constraints
1 ≤ n ≤ 100000
1 ≤ t
i
≤ 4
1 ≤ v
i
≤ 10
18
Explanation
The given inequalities are:
x > 10,
x < 9,
x = 7,
x ≠ 4.
For x=7, the inequalities 2, 3 and 4 are satisfied. | 32,288 |
Maximum Profit (BTCODE_D)
Chakra is a young and dynamic entrepreneur, who is developing rapidly as a successful hotelier. He owns the Quickbyte chain of restaurants, 'M' of which are fully functional now. He divides each day into 'N' time slots. For each time slot 'j', in every restaurant 'i', there are A
ij
waiters and B
ij
customers. Being a quality conscious person, he wants each waiter to handle at most one customer in a given time slot. Since he is really busy, in a day each restaurant is open only during one of the time slots. Since the hunger and demand for food varies during the day, the price which the customer is willing to pay varies, and is given by C
ij
for a restaurant 'i' during a time slot 'j'.
Given the values of A
ij
, B
ij
and C
ij
, find the maximum profit which Chakra can make in a day.
Input
The first line of input contains an integer 't', denoting the number of test cases.
For each testcase, the first line contains 2 space separated integers 'M' and 'N'.
Each of the next 'M' lines contains 'N' integers. The j
th
integer on the i
th
line denotes the value of A
ij
.
Each of the next 'M' lines contains 'N' integers. The j
th
integer on the i
th
line denotes the value of B
ij
.
Each of the next 'M' lines contains 'N' integers. The j
th
integer on the i
th
line denotes the value of C
ij
Output
For each test case output one value, denoting the maximum profit which Chakra can make in a day.
More than one restaurant can be open during a given time slot.
Constraints
t ≤ 50
1 ≤ M,N ≤ 100
1 ≤ A
ij
, B
ij
≤ 5000
0 ≤ C
ij
≤ 10
9
Example
Input:
1
2 3
1 2 3
3 2 1
3 2 1
1 2 3
4 5 2
3 1 6
Output:
16
Explanation
Test case 1: By opening the first restaurant at time slot 2 and second restaurant at time slot 3, Chakra makes a profit = 2×5 + 1×6 = 16. Note that although there are 3 customers for the second restaurant at time slot 3, since there is only 1 waiter, only 1 customer can be served. | 32,289 |
Recover Polynomials (BTCODE_E)
Venkatesh is an expert in mathematics, and loves playing around with polynomials during his free time. His favourite mathematical equation is pretty obviously: f(x) = a
n
*x
n
+ a
n-1
*x
n-1
+ ... + a
1
*x + a
0
. His friend Suhash loves posing challenges to Venkatesh. Once they were discussing a particular problem at Snacky, which goes as follows:
Suhash would choose an integer 'n' as the degree of the polynomial and give Venkatesh the value of the polynomial at 'n+1' equally spaced points, i.e. he gives Venkatesh integers 'n', 'x
0
', 'd' and g
0
, g
1
, g
2
... g
n
such that: f(x
0
) = g
0
, f(x
0
+d) = g
1
, f(x
0
+2*d) = g
2
... f(x
0
+n*d) = g
n
. Now, Venkatesh is required to find the polynomial. Since he hates floating point values, he decides to find the polynomial in coefficient form, modulo a prime number. Can you help Venkatesh find the polynomial?
Input
The first line of input contains an integer 't', denoting the number of test cases.
For each test case, the first line contains 3 space separated integers 'n', 'x
0
', 'd'. The next line contains 'n+1' space separated integers g
0
, g
1
, g
2
... g
n
.
Output
For each test case output 'n+1' integers, denoting the coefficients of the polynomial a
0
, a
1
, a
2
... a
n
. All the coefficients that are printed should be non-negative and should be less than 1000000007.
You are required to find coefficients of the polynomial a
0
, a
1
, a
2
... a
n
, which satisfy the equations: f(x
0
)%1000000007 = g
0
, f(x
0
+d)%1000000007 = g
1
... f(x
0
+n*d)%1000000007 = g
n
. It is guaranteed that there is a unique solution for every test case.
Constraints
t <= 25
1 <= n <= 1000
0 <= x
0
<= 100000
0 < d <= 10000
0 <= g
i
<= 10^9
Example
Input:
1
3 1 1
10 26 58 112
Output:
4 3 2 1
Explanation
Test case 1: It can be seen that the polynomial f(x) = x
3
+ 2*x
2
+ 3*x + 4 satisfies the above input. | 32,290 |
Life Game (BTCODE_F)
Gobo and Muku were really bored of working and decided to play a game on their respective laptops - the game of life. It is a one player game which consists of an M*N rectangular grid. Each cell of the grid contains exactly one magical potion. The potion at the j
th
column of the i
th
row of the grid increases the player's current health by V
ij
.(This value can be negative, in which case the player's health decreases). At any point of time, the health of a player can be negative too (i.e. He does not die). From a cell(i, j), the player can move to cells (i + 1, j - 1) or (i + 1, j) or (i + 1, j + 1), as long as these cells exist in the grid. Initially, the player has a health of 0. He can start from any column on the first row (1, j). If he chooses to enter a cell, then he is forced to drink the potion in that cell. The game is completed when any column of the last row is reached. There are 2 modes in which the game can be played: the "min" mode and the "max" mode. In "max" mode, the aim is to finish the game with maximum health H
max
satisfying the condition A ≤ H
max
≤ B. Similarly, in "min" mode the aim is finish the game with minimum health H
min
, satisfying the conditions A ≤ H
min
≤ B. Now, Gobo decides to play the game in "max" mode on his laptop, and Muku decides to play the game in "min" mode on his laptop. Can you help Gobo and Muku finish with maximum and minimum health respectively, satisfying the above conditions?
Input
The first line of input contains an integer 't', denoting the number of test cases.
For each test case, the first line contains 2 space separated integers 'M' and 'N'. The next line contains 2 space separated integers 'A' and 'B'. Each of the next 'M' lines contain 'N' integers. The j
th
integer on the i
th
line denotes the value V
ij
.
Output
Output 2 space separated integers H
min
and H
max
, the minimum and maximum health with which Gobo and Muku can finish the game. H
max
and H
min
should satisfy A ≤ H
max
, H
min
≤ B. If it is not possible to achieve such a health, output "NO" (quotes for clarity).
Gobo and Muku start playing on 2 different instances of the same game independently. i.e. the values of A, B and initial values of V
ij
are same for both grids.
Example
Input:
2
3 3
5 10
2 5 10
-1 -10 3
-3 6 -2
2 3
8 11
2 5 10
-1 -10 2
Output:
6 10
NO NO
Constraints
t ≤ 10
1 ≤ M, N ≤ 25
-1000 ≤ A ≤ B < 1000
-25 ≤ V
ij
≤ 25
Explanation
Test case 1: Take the path (1, 2) → (2, 1) → (3, 2), to get a value 5 - 1 + 6 = 10. Take the path (1, 2) → (2, 3) → (3, 3), to get a value 5 + 3 - 2 = 6.
Test case 2: There is no valid path which satisfies the above conditions. | 32,291 |
Coloring Trees (BTCODE_G)
Nivash and Bhoopathi play a game of memory, which goes as follows: There is a tree containing 'N' nodes, all of which are initially uncoloured. In the game, Nivash has 2 moves:
Command: Color a particular node with a given color.
Query: Ask Bhoopathi if the path from node 'a' to node 'b' (both inclusive), is monochromatic or not. (i.e Whether all nodes on the path have the same color).
Nivash can do these steps in any order he wishes and he colors each node at most once. Whenever Nivash puts forth a 'Query' at Bhoopathi, Bhoopathi has to recollect the colouring of the tree and reply either "YES" or "NO". Can your help Bhoopathi answer these queries?
Input
The first line of input contains an integer 'N', denoting the number of nodes in the tree. The next 'N-1' lines contain 2 space separated integers 'u' and 'v', denoting an edge between vertex 'u' and vertex 'v'.
The next line contains an integer 'Q', denoting the number of inputs (commands and queries) which Nivash wants to give. The next 'Q' lines contain 3 space separated integers 'x', 'a', 'b'. If 'x' is 1, it denotes a command to color node 'a' with a color 'b'. If 'x' is 2, it denotes a query and Bhoopathi should answer if the path from node 'a' to node 'b' (both inclusive), is monochromatic or not.
All vertices of the tree are 0 based.
Output
For each query, output "YES" or "NO" (quotes for clarity), denoting whether the path from node 'a' to node 'b' (both inclusive), is monochromatic or not.
Output "NO", even if all nodes on the path from node 'a' to node 'b' (both inclusive) are uncolored.
Constraints
1 ≤ N ≤ 100000
1 ≤ Q ≤ 200000
1 ≤ color value ≤ 30.
Example
Input:
3
0 1
1 2
7
1 0 11
2 0 1
2 0 2
1 2 12
1 1 11
2 0 1
2 0 2
Output:
NO
NO
YES
NO
Explanation
Initially node '0' is colored with color '11', so path between node '0' and node '1' is not monochromatic. Hence, the answer is "NO". The same explanation holds for the path between node '0' and node '2'. Then node '2' is colored with color '12' and node '1' with color '11'. Now, all nodes on the path between node '0' and node '1' are colored with only one color ('11'), so the answer is "YES". The path between node '0' and node '2' has 2 colors ('11' and '12'), hence the answer is "NO". | 32,292 |
Trie Expectation (BTCODE_H)
What is the expected number of nodes in a trie when 'N' words, each of length 'L' are inserted into it. The words are made up only of 0's and 1's. The words may be repeated and all possible permutations of words are equally likely. Initially the trie consists of only one node (root node).
Input
The first line of input contains an integer 't', denoting the number of test cases. Each of the next 't' lines contain 2 space separated integers 'N' and 'L'.
Output
For each test case, output one floating point value denoting the expected number of nodes in the trie. Output the values rounded off to 2 decimal places. Always print 2 digits after the decimal point.
To know more about tries visit
here
.
Example
Input:
2
1 3
2 2
Output:
4.00
4.25
Constraints
t ≤ 25
1 ≤ N ≤ 300
1 ≤ L ≤ 300
Explanation:
Test case 1: There are 8 possible words of length 3. Which ever word is inserted into the trie, we get only 4 nodes. | 32,293 |
Permutation Game (BTCODE_I)
Harsha is given 9 integers a
1
, a
2
, a
3
... a
9
. This denotes that he is given a
1
1's, a
2
2's ... a
9
9's. Let 'x' = (a
1
+ a
2
+ ... a
9
). Now, Harsha makes all possible 'x' digit numbers by using these given digits. Let S be the set of all such numbers which he makes. Now he constructs a directed graph containing |S| nodes, in which each node denotes a unique number from the set. For all numbers u, v belonging to S, there is a directed edge from node 'u' to node 'v in the graph iff u > v. It is easy to note that we obtain a directed acyclic graph. What's more, the edges of the graph are weighted. The weight of an edge joining node 'u' and node 'v' is equal to u + v. Now, Deepak decides to test Harsha's memory and gives him 'Q' queries. Each query consists of two numbers 'u', 'v' (u > v, both belonging to the set S). For each query Harsha must provide the following answers:
How many distinct paths are there from node 'u' to node 'v' in the graph.
For each distinct path 'i' from node 'u' to node 'v', let S
i
denote the sum of weights of all edges on this path. Calculate the value of sum(S
i
), for every distinct path 'i' from node 'u' to node 'v'.
Input
The first line of input contains 9 integers a
1
, a
2
... a
9
. The second line contains a single integer 'Q', denoting the number of queries. Each of the next 'Q' lines contain 2 numbers 'u' and 'v'.
Output
For each query, output two space separated integers denoting the number of distinct paths and sum of weights of all paths respectively. Since the output can be large, output these quantities modulo 1000000007.
Two paths (v
1
, v
2
... v
m
) and (u
1
, u
2
... u
n
) are distinct if:
m ≠ n
m = n, there exists some index 'k' (1 ≤ k ≤ m) such that v
k
≠ u
k
Constraints
1 ≤ (a
1
+ a
2
+ ... a
9
) ≤ 500
1 ≤ Q ≤ 20
a
i
≥ 0
Example
Input:
2 0 1 0 0 0 0 0 0
1
311 113
Output:
2 1110
Explanation
Test case 1: The set S for the above problem is {311, 113, 131}. The edges of the graph are 311→131, 311→113, 131→113. There are two distinct paths from 311 to 113, namely (311→131→113) and (311→113). The sum of weights of edges on path-1 = (311 + 131) + (131 + 113) = 686. For path-2, the sum of weights of edges = (311 + 113) = 424. Therefore, answer = 686 + 424 = 1110. | 32,294 |
Grid Tiling (BTCODE_J)
Vikas is the chief interior designer in charge of the Taj Palace, Mumbai. He wants to make an impressive and colourful pattern in the courtyard. Importing exotic tiles has become very difficult after the Mumbai terror attacks, and therefore Vikas has only 4 kinds of tiles to choose from:
A B C D
== == == ==
XX X X X
XX X XX
Any rotation of above tiles is also permitted.
Each tile is available in 'k' different colors, and there's an infinite supply of all tiles. The courtyard has dimensions 2 * 'n'. Vikas wants to tile the courtyard in such a way that no two adjacent tiles have the same color. Two tiles are considered adjacent if they share a common side. Two tilings are considered different if:
1) The arrangement of tiles is different.
2) There is at least 1 position (1*1 square) which has different colors in the two arrangements.
Can you help Vikas find the number of different ways in which he can tile the courtyard, subject to the above conditions?
Input
The first line of input contains a single integer 't', denoting the number of test cases.
Each of the next 't' lines contains 2 space separated integers 'n' and 'k'.
Output
For each test case output one integer, denoting the number of different ways in which the courtyard can be tiled.
Two tiles are considered adjacent if they share an edge. Two tiles which just share a common point are not considered adjacent.
Since the answers can be large, print all the quantities modulo 1000000007.
Constraints:
t <= 1000
1 <= n <= 10^9
1 <= k <= 1000
Example
Input:
2
1 1
1 2
Output:
1
4
Explanation:
Test case 1: There is only 1 way to tile the courtyard, by using a 2*1 tile.
Test case 2: Let '1' and '2' be the available colors. The grid can be tiled in 4 ways - 1) place one 2*1 tile of color '1', 2) place one 2*1 tile of color '2', 3) Place two 1*1 tiles (color '1' above and color '2' below), 4) Place two 1*1 tiles (color '2' above and color '1' below) | 32,295 |
Array Sorting (BTCODE_K)
Sumit specialises in sorting algorithms, and Abhishek decides to test Sumit's coding skills. An array of 'n' numbers a[0], a[1], a[2] ... a[n-1] is given. Abhishek gives a sequence of inputs of the form "v i j". Each input is either a query or an update (query if 'v' is 0, update otherwise).
For any input of the form "0 i j", Sumit's output should be as follows:
If the subarray a[i], a[i+1] ... a[j] is unsorted, output 0.
If the subarray a[i], a[i+1] ... a[j] is sorted in non-descending order, output 1.
If the subarray a[i], a[i+1] ... a[j] is sorted in non-ascending order, output 2.
If the subarray a[i], a[i+1] ... a[j] is sorted in both non-ascending and non-descending order (i.e., if all the elements in the range are equal), output 3.
Any other input "v i j" (v!=0) should be treated as an update, as follows:
For each element in the subarray a[i], a[i+1] ... a[j], Sumit has to replace the element a[k] with v-a[k].
Sumit is really tired and does not want to write a program. Can you write a program for Sumit, which responds to Abhishek's instructions?
Input
The first line of input contains 2 space separated integers 'n' and 'q'. The second line contains 'n' integers a[0], a[1] ....., a[n-1]. Each of the next 'q' lines contain 3 integers 'v', 'i', 'j'.
Output
For each query, output a single integer 0, 1, 2 or 3, denoting the answer.
Example
Input:
4 5
3 -2 -5 1
1 1 3
0 0 3
0 0 2
0 2 3
0 0 1
Output:
0
1
2
3
Constraints
1 <= n <= 100000
1 <= q <= 100000
-5000 <= a[i] <= 5000
-5000 <= v <= 5000
Explanation
Initial array is {3, -2, -5, 1}. After first update, the array will be {3, 3, 6, 0}. Now, from indices '0' to '3', it is unsorted. From indices '0' to '2', it is sorted in non-descending order. From indices '2' to '3', it is sorted in non-ascending order. Between indices '0' and '1', the values are equal. | 32,296 |
Revenge of the squares (variation) (SQUAREV1)
Given a number N calculate the number R of different presentations of N in the form A*A+B*B with A and B being positive integers including zero. 1*1+2*2 and 2*2+1*1 are not different presentations. So for input 5 the output is 1.
Input
Fifty tests with one positive integer < 10^9.
Output
Print the illustrated above number R for each test.
Example
Input:
5
7
986244509
Output:
1
0
2 | 32,297 |
Kolica (KOLICA)
A number of shopping carts filled with explosives are floating in a coordinate system, in one of the four main directions (up, down, left or right). All carts are moving at a speed of one unit per second.
Movement is continuous; for example, in one third of a second, a cart travels one third of a unit.
When two or more carts collide (are at the same place at the same time), there is an explosion and all carts taking part in the collision explode and cease to exist.
Write a program that, given the starting points and directions of all carts, determines which carts never explode.
Input
The first line of input contains an integer N (2 ≤ N ≤ 500), the number of carts.
Each of the following N lines contains two integers and a string. Each pair of integers describes the starting coordinates of one cart (between 0 and 100 000 000, inclusive), and the string describes the direction in which the cart is moving ("gore" for up, "dolje" for down, "lijevo" for left, or "desno" for right).
No two carts will start at the same coordinates.
Output
Output the indices of all carts which never explode, sorted in ascending order, one index per line. The first cart in the input is labeled 1, the second is labeled 2 etc. If no carts survive, output "nema".
Example
Input:
4
5 5 dolje
5 6 lijevo
5 7 desno
5 8 gore
Output:
1
2
3
4
Input:
5
3 3 dolje
1 1 desno
5 1 lijevo
100000 500000 desno
900000 500000 lijevo
Output:
nema
Input:
3
10 0 gore
0 10 desno
15 5 lijevo
Output:
2 | 32,298 |
Problem 3 (NOVICE43)
When I first learned backtracking I made a program to find all the permutations of the English alphabet in lexicographically increasing order. Filled with elation I showed the program to Rohil. Rohil being someone who likes to do stuff off the league was not impressed and gave me the following variation of the problem help me to solve the problem:
You have to find the number of permutations of length N (1 ≤ N ≤ 11) such that at whenever a character (say 'c' ) appears in the permutation all the characters smaller than 'c' should have appeared before it at least once. A character is smaller than another if it appears before the other in the English alphabet. ‘a’ being the smallest and ‘z’ being the largest. For example when N=2 then aa, ab are the only valid permutations and ba, bb are invalid since in ba all the characters smaller than b have not appeared at least once before it. See example for further clarification.
Input
Line 1: T (number of test cases)
Line 2: n1
Line 3: n2
…
…
Output
Line 1: number of such permutations of length n1
…
...
Example
Input:
2
2
3
Output:
2
5
Explanation for N=3, the possible permutations are: abc, aba, abb, aab, aaa | 32,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.