task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Your Rank is Pure (GCJPURE)
Pontius
: You know, I like this number 127, I don't know why.
Woland
: Well, that is an object so pure. You know the
prime numbers
.
Pontius
: Surely I do. Those are the objects possessed by our ancient masters hundreds of years ago. Oh, yes, why then? 127 is indeed a prime number as I was told.
Woland
: Not... only... that. 127 is the 31st prime number; then, 31 is itself a prime, it is the 11th; and 11 is the 5th; 5 is the 3rd; 3, you know, is the second; and finally 2 is the 1st.
Pontius
: Heh, that is indeed... purely prime.
The game can be played on any subset
S
of positive integers. A number in
S
is considered pure with respect to
S
if, starting from it, you can continue taking its rank in
S
, and get a number that is also in
S
, until in finite steps you hit the number 1, which is not in
S
.
When
n
is given, in how many ways you can pick
S
, a subset of {2, 3, ..., n}, so that
n
is pure, with respect to
S
? The answer might be a big number, you need to output it modulo 100003.
Input
The first line of the input gives the number of test cases,
T
.
T
lines follow. Each contains a single integer
n
.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the answer as described above.
Limits
T
≤ 200.
2 ≤
n
≤ 500.
Sample
Input:
2
5
6
Output:
Case #1: 5
Case #2: 8 | 33,200 |
The Fox and the Wolf (FOXWOLF)
In a certain peaceful forest, there live a Fox and a Wolf. Due to common misconception, one might suppose that the Wolf would want to hunt the Fox – however, both are in fact nice animals, and get along just fine. Indeed, they have such nice manners that, if they ever meet up, they will have a nice little chat for $C$ minutes ($1 \leq C \leq 9$).
The forest that the Fox and the Wolf live in can be regarded as a rectangle, $N$ km long along its East side and $M$ km wide along its North side ($1 \leq N,M \leq 20$). It is divided into a grid of squares, each with a side length of 1 km. Each such square either contains a meadow (represented by a ‘.’), is full of burrs (‘B’), is blocked by trees (‘T’), contains the Fox’s den (‘F’), contains the Wolf’s lair (‘W’), currently contains the Fox (‘f’), or currently contains the Wolf (‘w’).
At the end of a long day at work (consisting of solving complex computer science problems in their heads), both animals wish to get to their respective homes as soon as possible. Every minute, each of them can walk one km directly North, East, South, or West, or just stay put – however, they cannot enter squares blocked by trees, nor can they enter each other’s homes (that wouldn’t be very polite). They also don’t want to leave the forest, seeing as humans jealous of their supreme intellect are constantly lurking just outside.
Every time the Fox or the Wolf goes from a square full of burrs to a meadow, he must stand still and spend $B$ minutes ($1 \leq B \leq 9$) picking burrs off of himself. As mentioned above, they must also stop and chat if they meet up. Though each square is quite big, the animals always walk to its exact centre before moving on. This means that they will meet up if they either occupy the same square at the same time, or if they pass each other while walking between squares (which would happen if they switched positions in the space of a minute). Once the animals have chatted once, they never have to chat again, having already satisfied the demands of etiquette. Both animals are great multitaskers, and can pick burrs while chatting with each other.
Each animal wants to get home as soon as possible, but is also considerate of the other – as such, they will collaborate so as to minimize the time for both of them to get home. Due to their extreme intelligence, both animals will calculate this minimum time in their heads instantly – however you, the observer, will probably need to write a program to figure it out...
Input
Line $1$: 4 integers, $N$, $M$, $C$, and $B$
Next $N$ lines: $M$ characters each, representing a row of the forest as described above
Output
A single integer – the minimum time for both the Fox and the Wolf to get to their respective homes, in minutes. If this is impossible, output -1 instead.
Example
Input:
5 6 5 1
......
BWTTTB
B.TB..
BBT..T
.FTfw.
Output:
17
Explanation of Sample:
The Wolf should wait for the first three minutes, letting the Fox go first. From then on, the Fox can continue along its only possible route home. The Wolf will be 2 squares behind the Fox most of the time, except for when it enters the burr-filled square, when it will temporarily be 1 behind. With this strategy, the Wolf will take 14 minutes to get home, while the Fox will take 17, and since we only care about the larger, the total time is 17 minutes. | 33,201 |
Foxlings (FOXLINGS)
It’s Christmas time in the forest, and both the Fox and the Wolf families are celebrating. The rather large Fox family consists of two parents as well as $N$ ($1 \leq N \leq 10^9$) little Foxlings. The parents have decided to give their children a special treat this year – crackers! After all, it’s a well-known fact that Foxen love crackers.
With such a big family, the parents can’t afford that many crackers. As such, they wish to minimize how many they give out, but still insure that each Foxling gets at least a bit. The parents can only give out entire crackers, which can then be divided and passed around.
With this many children, not all of them know one another all that well. The Foxlings have names, of course, but their parents are computer scientists, so they have also conveniently numbered them from $1$ to $N$. There are $M$ ($1 \leq M \leq 10^5$) unique two-way friendships among the Foxlings, where relationship $i$ is described by the distinct integers $A_i$ and $B_i$ ($1 \leq A_i,B_i \leq N$), indicating that Foxling $A_i$ is friends with Foxling $B_i$, and vice versa. When a Foxling is given a cracker, he can use his tail to precisely split it into as many pieces as he wants (the tails of Foxen have many fascinating uses). He can then pass these pieces around to his friends, who can repeat this process themselves.
Input
Line $1$: 2 integers, $N$ and $M$
Next $M$ lines: 2 integers, $A_i$ and $B_i$, for $i=1..M$
Output
A single integer – the minimum number crackers must be given out, such that each Foxling ends up with at least a small part of a cracker.
Example
Input:
9 5
3 1
6 1
7 6
2 7
8 9
Output:
4
Explanation of Sample:
The parents can give one cracker to Foxling 6, who will then split it into three and give pieces to his friends (Foxlings 1 and 7). Foxling 7 can then give half of his piece to his other friend, Foxling 2.
They can give another cracker to Foxling 8, who will split it with Foxling 9.
This leaves Foxlings 4 and 5, who have no friends (don’t worry, Foxen have long since outgrown the need for friends), and who must be given one cracker each. This brings the total up to 4 crackers. | 33,202 |
Boxdropper (BOXD)
The University of Waterloo is famous for its booming population of geese, and many researchers go there to study them. One day, Doctor Y (known for his work in the field of boxology) decided to go there and investigate how good geese are at optimization problems.
At UW, there is a large lake (so large, in fact, that the boundaries are never an issue). Doctor Y decides to drop a number of 2D boxen onto this lake and command the geese to travel from one to another, recording how much time they spend flying as opposed to walking (naturally, the geese won’t swim, considering the not-so-appealing brown colour of the lake). He has a Boxdropper machine at his disposal to do the work for him – he can give it the following commands:
B
$x_1$ $y_1$ $x_2$ $y_2$: Drop a box onto the lake such that its lower-left coordinate is at ($x_1$, $y_1$) and its upper-right coordinate is at ($x_2$, $y_2$). Doctor Y defines the origin to be somewhere in the middle of the lake. Note that boxen can overlap with one another.
G
$a$ $b$: Command the geese to travel from the
a
th
box dropped to the
b
th
one, and record the total distance that they fly.
Since the scientific community has not yet realized the benefits of studying boxen, Doctor Y isn’t receiving much funding – as such, he only has $500$ boxen at his disposal, and his machine can only handle $10^6$ commands before it overheats.
The geese can walk across boxen freely, but sometimes they may have to fly over water to reach other boxen. The geese, secretly participating in the second stage of the Canadian Computing Competition every year, are well versed in optimization problems such as these, and so will always choose a path that will minimize the total distance that they spend flying. Given the commands that Doctor Y inputs into the Boxdropper, determine the distances recorded by it (one for every
G
command).
Input
On each line, one of the 2 types of commands will be given:
If the line starts with the character
B
, it will be followed by 4 integers ($x_1$, $y_1$, $x_2$, and $y_2$), each with absolute value no greater than $10^6$.
If the line starts with the character
G
, it will be followed by 2 integers ($a$ and $b$), with $a \neq b$ and $1 \leq a,b \leq n$ (where $n$ is the number of
B
commands inputted so far).
Commands should be read until EOF.
Output
For every
G
command, output the distance that the geese spend flying. The numbers should be printed one per line, and rounded off to 2 decimal places.
Example
Input:
B -1 2 1 5
B 3 -4 4 1
G 2 1
B 4 -3 6 -2
B 6 -6 8 -4
G 2 3
G 1 4
Output:
2.24
0.00
3.24
Explanation of Sample:
The lake looks like this:
For the first
G
command, the geese must fly along the red line, which has a length of √5.
For the second, the two boxen are touching, so no flight is necessary.
For the third, the geese must first fly along the red line, then walk across boxen 2 and 3, and finally fly along the blue line, which has a length of 1. | 33,203 |
All Your Base (GCJ1C09A)
In A.D. 2100, aliens came to Earth. They wrote a message in a cryptic language, and next to it they wrote a series of symbols. We've come to the conclusion that the symbols indicate a number: the number of seconds before war begins!
Unfortunately we have no idea what each symbol means. We've decided that each symbol indicates one digit, but we aren't sure what each digit means or what base the aliens are using. For example, if they wrote "ab2ac999", they could have meant "31536000" in base 10 -- exactly one year -- or they could have meant "12314555" in base 6 -- 398951 seconds, or about four and a half days. We are sure of three things: the number is positive; like us, the aliens will never start a number with a zero; and they aren't using unary (base 1).
Your job is to determine the minimum possible number of seconds before war begins.
Input
The first line of input contains a single integer,
T
.
T
test cases follow. Each test case is a string on a line by itself. The line will contain only characters in the 'a' to 'z' and '0' to '9' ranges (with no spaces and no punctuation), representing the message the aliens left us. The test cases are independent, and can be in different bases with the symbols meaning different things.
Output
For each test case, output a line in the following format:
Case #
X
:
V
Where
X
is the case number (starting from 1) and
V
is the minimum number of seconds before war begins.
Limits
1 ≤
T
≤ 100
1 ≤ the length of each line < 61
The answer will never exceed 10
18
Sample
Input
3
11001001
cats
zig
Output
Case #1: 201
Case #2: 75
Case #3: 11 | 33,204 |
Center of Mass (GCJ1C09B)
You are studying a swarm of
N
fireflies. Each firefly is moving in a straight line at a constant speed. You are standing at the center of the universe, at position (0, 0, 0). Each firefly has the same mass, and you want to know how close the center of the swarm will get to your location (the origin).
You know the position and velocity of each firefly at t = 0, and are only interested in t ≥ 0. The fireflies have constant velocity, and may pass freely through all of space, including each other and you. Let M(t) be the location of the center of mass of the
N
fireflies at time t. Let d(t) be the distance between your position and M(t) at time t. Find the minimum value of d(t), d
min
, and the earliest time when d(t) = d
min
, t
min
.
Input
The first line of input contains a single integer
T
, the number of test cases. Each test case starts with a line that contains an integer
N
, the number of fireflies, followed by
N
lines of the form
x y z vx vy vz
Each of these lines describes one firefly: (x, y, z) is its initial position at time t = 0, and (vx, vy, vz) is its velocity.
Output
For each test case, output
Case #X: d
min
t
min
where
X
is the test case number, starting from 1. Any answer with absolute or relative error of at most
10
-6
will be accepted.
Limits
All the numbers in the input will be integers.
1 ≤
T
≤ 100
The values of x, y, z, vx, vy and vz will be between -5000 and 5000, inclusive.
Large dataset
3 ≤
N
≤ 500
Sample
Input
3
3
3 0 -4 0 0 3
-3 -2 -1 3 0 0
-3 -1 2 0 3 0
3
-5 0 0 1 0 0
-7 0 0 1 0 0
-6 3 0 1 0 0
4
1 2 3 1 2 3
3 2 1 3 2 1
1 0 0 0 0 -1
0 10 0 0 -10 -1
Output
Case #1: 0.00000000 1.00000000
Case #2: 1.00000000 6.00000000
Case #3: 3.36340601 1.00000000
Notes
Given
N
points (x
i
, y
i
, z
i
), their center of the mass is the point (x
c
, y
c
, z
c
), where:
x
c
= (x
1
+ x
2
+ ... + x
N
) / N
y
c
= (y
1
+ y
2
+ ... + y
N
) / N
z
c
= (z
1
+ z
2
+ ... + z
N
) / N | 33,205 |
Bribe the Prisoners (GCJ1C09C)
Problem
In a kingdom there are prison cells (numbered 1 to
P
) built to form a straight line segment. Cells number
i
and
i+1
are adjacent, and prisoners in adjacent cells are called "neighbours." A wall with a window separates adjacent cells, and neighbours can communicate through that window.
All prisoners live in peace until a prisoner is released. When that happens, the released prisoner's neighbours find out, and each communicates this to his other neighbour. That prisoner passes it on to
his
other neighbour, and so on until they reach a prisoner with no other neighbour (because he is in cell 1, or in cell
P
, or the other adjacent cell is empty). A prisoner who discovers that another prisoner has been released will angrily break everything in his cell, unless he is bribed with a gold coin. So, after releasing a prisoner in cell
A
, all prisoners housed on either side of cell
A
- until cell 1, cell
P
or an empty cell - need to be bribed.
Assume that each prison cell is initially occupied by exactly one prisoner, and that only one prisoner can be released per day. Given the list of
Q
prisoners to be released in
Q
days, find the minimum total number of gold coins needed as bribes if the prisoners may be released in any order.
Note that each bribe only has an effect for one day. If a prisoner who was bribed yesterday hears about another released prisoner today, then he needs to be bribed again.
Input
The first line of input gives the number of cases,
N
.
N
test cases follow. Each case consists of 2 lines. The first line is formatted as
P Q
where
P
is the number of prison cells and
Q
is the number of prisoners to be released.
This will be followed by a line with
Q
distinct cell numbers (of the prisoners to be released), space separated, sorted in ascending order.
Output
For each test case, output one line in the format
Case #X: C
where
X
is the case number, starting from 1, and
C
is the minimum number of gold coins needed as bribes.
Limits
1 ≤
N
≤ 100
Q
≤
P
Each cell number is between 1 and
P
, inclusive.
Large dataset
1 ≤
P
≤ 10000
1 ≤
Q
≤ 100
Sample
Input
2
8 1
3
20 3
3 6 14
Output
Case #1: 7
Case #2: 35
Note
In the second sample case, you first release the person in cell 14, then cell 6, then cell 3. The number of gold coins needed is 19 + 12 + 4 = 35. If you instead release the person in cell 6 first, the cost will be 19 + 4 + 13 = 36. | 33,206 |
Boxlings (BOXLINGS)
Doctor Y, always eager to further his research in the field of boxology, is observing a family of boxen in their natural habitat – a barrel of wine. He has noticed that in addition to the $N$ ($1 \leq N \leq 200,000$) rectangular, two-dimensional boxen, there are $M$ ($1 \leq M \leq 200,000$) almost imperceptible points floating on the surface of the wine. He reasons that these must be baby boxen – also known as boxlings.
Curious as to the customs of box families, Doctor Y wishes to count how many boxlings are floating on top of boxen. From his top-down view of the barrel, he has divided the surface of the wine into a two-dimensional Cartesian plane, and noted the positions of all the boxen and boxlings. Each box occupies a rectangular region parallel to the axes of the plane, with two of its opposite corners at coordinates ($x_1$, $y_1$) and ($x_2$, $y_2$). Doctor Y has observed that boxen sometimes overlap with one another. On the other hand, each boxling is so small that it occupies only a single point on the plane, with x-coordinate $a$ and y-coordinate $b$. All coordinates have absolute values no larger than $10^9$.
Having recorded the locations of all of the life forms on the surface of the wine, Doctor Y is interested in counting exactly how many boxlings are floating on top of at least one box. Note that if a boxling is on the very edge or corner of a box, it counts as being on top. Also note that two boxlings can occupy the exact same locations, in which case they should still be counted separately. It's also possible for a box to have zero area, in which case it's treated as a line (or point) and can still have boxlings on top of it.
With so many boxen and boxlings living in this wine barrel, Doctor Y doesn’t feel like sitting there and counting them all by hand, crazy though he is. As such, he wants you to write a program to, given the locations of all the boxen and boxlings, count the number of boxlings that are floating on top of at least one box. Don’t worry - your hard work will surely lead to exciting discoveries in the field of boxology.
Input
Line $1$: 2 integers, $N$ and $M$
Next $N$ lines: 4 integers, $x_1$, $y_1$, $x_2$, and $y_2$, the coordinates of each box
Next $M$ lines: 2 integers, $a$ and $b$, the coordinates of each boxling
Output
A single integer – the number of boxlings that are on top of at least one box.
Example
Input:
5 10
-1 -1 2 5
4 -3 5 3
1 2 4 4
5 -6 8 -4
1 -2 8 0
1 4
5 4
2 2
3 1
6 -5
5 -1
3 -3
-1 -2
-1 -1
2 -1
Output:
6
Explanation of Sample
Below is a top-down view of the surface of the wine:
The coloured-in rectangles are the boxen, the red dots are boxlings that are on top of at least one box, and the blue dots are the other boxlings. Counting the red dots, it can be seen that there are six of them. | 33,207 |
Crazy Shopkeeper (CRAZYSK)
Zoglu Bepari is a peculiar shopkeeper of Chittagong. He is a very famous shopkeeper. Everyone loves him and gave him a nick name ‘MAMU’. He has a beautiful small shop which is also known as “MAMUR DOKAN”. From morning to late night, he sells non-stop. His shop always remains over-crowded as he gives some weird and crazy offers almost every day. Most of the offers favor customers. He recently created a special offer for his customers. For each item he sells, he gives a special card. These cards are rare and only available in his shop. And no one can cheat with him showing fake cards as he is really good at checking cards. Suppose, a customer bought
X
items, he gives a positive number
N
along with
X
cards to the customer. Another important thing is customers can return
N
cards for collecting another item of same type and a card in exchange.
Now as a programmer, you just have to calculate the total number of items a customer can get after using maximum number of cards he gets.
Input
Input starts with an positive integer
T < 100
followed by T lines. Each of these lines contain two positive integers, number of item (X) bought in the first deal
1 < X <= 2^64
, and number(N) that is given by Mamu
1 < N <= X
.
Output
Print the total number of items the customer will have after exchanging
maximum
number of cards for getting extra items.
Example
Input:
5
15 3
2147483647 2
34 3
231 2
5 2
Output:
22
4294967293
50
461
9 | 33,208 |
digit count (DIGCNT)
Given two integers a and b, we write the numbers between a and b, inclusive, in a list. Your task is to calculate the number of occurrences of each digit except zero.
For example, if a = 1024 and b = 1032, the list will be 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032.
There are ten 1s, seven 2s, three 3s, etc.
Input
The input consists of up to 500 lines. Each line contains two numbers a and b, where 1 <= a, b <= 10^16. The input terminates when a is 0.
Output
For each pair of input, output a line containing ten numbers separated by single spaces. The first number is the number of occurrences of the digit 1,
the second is the number of occurrences of the digit 2, etc.
Example
input
1 10
0 0
output
2 1 1 1 1 1 1 1 1 | 33,209 |
Union Laser (ULASER)
Doctor Y, a leading expert in the field of boxology, is investigating the properties of boxen with his expensive super-precision laser. In particular, he plans to position the laser inside the union of a bunch of boxen, and see where the beam collides with itself.
Since Doctor Y blew all his cash on the laser, he can’t actually afford to purchase boxen to conduct his experiment – instead, he will simulate it on his old computer, which uses an integer grid system. He will give his computer an integer $N$, the number of boxen ($1 \leq N \leq 10,000$), as well as their descriptions. Each box is described by 4 integers, $x_1$, $y_1$, $x_2$, and $y_2$, and is an axis-aligned rectangle with coordinates ($x_1$, $y_1$) and ($x_2$, $y_2$) describing a pair of its opposite corners. Boxen may overlap with one another. He will also input the location of the laser ($A$, $B$), such that it will be positioned strictly within at least one of the boxen. The laser points down and right at a 45° angle. All coordinates have absolute values of at most $3000$.
As it turns out, boxen are made of a perfectly reflective material (a fact which Doctor Y will discover upon completion of his experiment) – as such, whenever the laser beam hits the edge of the union of the boxen, it bounces off. For example, if it hits a vertical edge from the left, it bounces to the right, with the up-down direction preserved. If it hits a corner head-on, it will reverse direction, hence colliding with itself right at the corner. Normally, light travels quite fast, but due to the mysterious properties of boxen, the speed of light when inside a box union is only √2 units/second.
Doctor Y plans to use his computer to simulate the path of the laser and see when and where it first collides with itself, but there’s one problem – he doesn't know how to program! Offering non-cafeteria food, he lures a desperate Waterloo student into his lab, where he forces him (or her?) to write the laser simulation program. That’s you.
Input
Line $1$: 1 integer, $N$
Line $2$: 2 integers, $A$ and $B$
Next $N$ lines: 4 integers, $x_1$, $y_1$, $x_2$, and $y_2$, describing the coordinates of each box
Output
If the laser beam never collides with itself or the laser, simply output “Time limit exceeded”.
If the laser beam collides with the actual laser (at coordinates ($A$, $B$)) before it collides with another location through which the beam has already passed, the first line of output should consist of a single number – the amount of time that passes before laser beam collides with the laser, in seconds. The second line should read “Broken equipment”.
Otherwise, the first line of output should consist of a single number – the amount of time that passes before laser beam first collides with itself, in seconds. The second line should contain a pair of numbers – the x and y coordinates of where this takes place.
Each number should be rounded off to 1 decimal place.
Example
Input:
7
0 4
-1 5 1 -1
0 -2 4 2
0 -4 1 2
2 -4 5 -1
5 2 7 4
3 -5 4 -4
0 -6 3 -4
Output:
12.0
0.0 0.0
Explanation of Sample
The grid looks like this:
The filled-in squares represent squares that are part of at least one box – together, they make up the box union. Note that the union can have holes in it, and that it can be disjoint.
The blue lines denote the boundaries of the union – these are the lines that the laser can bounce off of.
The yellow lines are edges of boxen that do not contribute to the union – the laser can go through these freely.
The red diamond is the position of the laser, and the red line is the path that the laser beam follows. Note that when it bounces off the corner at (2,-2), since it didn’t hit it head-on, it is the same as bouncing off of a horizontal edge.
Following the path of the laser beam, it can be seen that it collides with itself at (0,0). Before this, it has travelled 12√2 units, which takes exactly 12 seconds.
More Examples:
If the laser were positioned at (0,3), the output should be:
12.0
0.0 -1.0
If the laser were positioned at (0,1), the output should be:
5.0
5.0 -4.0
If the laser were positioned at (0,0), the output should be:
8.0
Broken equipment | 33,210 |
Sales (SALES)
Bosco has gotten his hands on $B$ ($1 \leq B \leq 50$) dollars! Being a Magic the Gathering™ enthusiast, he wishes to spend some amount of his budget on cards to improve his deck.
He has located a local store that has $N$ ($1 \leq N \leq 30,000$) cards for sale. Card $i$ costs $c_i$ ($1 \leq c_i \leq 50$) dollars, and will improve Bosco’s DQI (Deck Quality Index) by $v_i$ ($1 \leq v_i \leq 1000$) points. Only one copy of each card is for sale.
Business hasn’t been too great lately, so the store is offering sales on various days. Though the term “price adjustments” would be more accurate, as card prices can increase, “sales” are much more appealing – and, indeed, Bosco wants to go do all of his shopping on one of the $D$ ($1 \leq D \leq 3000$) days of the sales. In fact, he’s already acquired a list of the price adjustments that will be made.
On day $i$, the cost of card $a_i$ ($1 \leq a_i \leq N$) is changed to $b_i$ ($1 \leq b_i \leq 50$), while all other cards remain unchanged. That is, before day $1$, all cards have their initial costs ($c_{1..N}$), and from then on, price adjustments accumulate from day to day.
Additionally, on each day, only certain cards from the store’s inventory are actually up for sale. In particular, on day $i$, only cards $x_i$ to $y_i$ ($1 \leq x_i \leq y_i \leq N$), inclusive, may be purchased.
Bosco doesn’t care how much of his budget he spends, but he absolutely must have the best possible deck. As such, for each of the $D$ days, he wants to consider buying some (possibly empty) set of cards, such that the sum of their costs is no larger than $B$, and the sum of their DQI points is maximal. Determine this DQI sum for each day, so that Bosco will know when to go to take full advantage of the “sales”.
Input
Line $1$: 3 integers, $B$, $N$, and $D$
Next $N$ lines: 2 integers, $c_i$ and $v_i$, for $i=1..N$
Next $D$ lines: 4 integers, $a_i$, $b_i$, $x_i$, and $y_i$, for $i=1..D$
Output
For each day, output the maximal DQI sum of cards up for purchase that day which Bosco can purchase without going over his budget, considering all price changes that have occurred so far.
Example
Input:
5 5 3
9 6
1 5
2 3
3 11
2 7
1 1 1 4
4 6 3 5
4 1 1 4
Output:
22
10
25
Explanation of Sample:
At first, the 5 cards (with point values 6, 5, 3, 11, and 7, respectively) have costs of 9, 1, 2, 3, and 2 dollars, in that order.
On the first day, the cost of the first card is reduced to 1 dollar, and the first 4 cards are up for purchase.
On the second day, the cost of the fourth card is increased to 6 dollars, and only the last 3 cards can be bought.
On the final day, the cost of card 4 is changed again, this time to 1 dollar, and the first 4 cards are once again considered.
On the first day, Bosco should buy the first, second, and fourth cards, costing a total of 5 dollars.
On the second, cards 3 and 5 should be purchased with 4 dollars, as card 4 is now too expensive.
On the final day, all of the cards up for sale can be bought for 5 dollars. Notice that card 1 still costs 1 dollar, from the first price change. | 33,211 |
STUDENTS (AU7_5)
Professor X wants to position N (1 ≤ N ≤ 100,000) girls and boys in a single row to present at the annual fair.
Professor has observed that the boys have been quite pugnacious lately; if two boys too close together in the line, they will argue and begin to fight, ruining the presentation. Ever resourceful, Professor calculated that any two boys must have at least K (0 ≤ K < N) girls between them in order to avoid a fight.
Professor would like you to help him by counting the number of possible sequences of N boys and girls that avoid any fighting. Professor considers all boys to be the same and all girls to be the same; thus, two sequences are only different if they have different kinds of students in some position.
Input
First line contains C (1 ≤ C ≤ 20) the number of test cases.
Next C lines contain N and K.
Output
A single integer representing the number of ways Professor could create such a sequence of students. Since this number can be quite large, output the result modulo 5000011.
Sample
Input
1
4 2
Output
6
Explanation
The possible sequences are GGGG, BGGG, GBGG, GGBG, GGGB, or BGGB. | 33,212 |
Box Factory (GCJ121CC)
You own a factory with two assembly lines. The first assembly line makes boxes, and the second assembly line makes toys to put in those boxes. Each type of box goes with one type of toy and vice-versa.
At the beginning, you pick up a box from the first assembly line and a toy from the second assembly line. You then have a few options.
You can always throw out the box and pick up the next one.
You can always throw out the toy and pick up the next one.
If the box and toy are the same type, you can put the toy in the box, and send it out to customers.
You always pick boxes up in the order in which they are made, and similarly for toys. You know the order in which boxes and toys are made, and you want to plan out a strategy that will allow you to send as many boxed toys as possible to customers.
Warning: The two assembly lines make a lot of boxes and toys. However, they tend to make one kind of thing for a long period of time before switching.
Input
The first line of the input gives the number of test cases, T. T test cases follow.
Each test case begins with a line contains two integers N and M. It is followed by a line containing 2 * N integers a1, A1, a2, A2, ... aN, AN, and another line containing 2 * M integers b1, B1, b2, B2, ... bM, BM.
This means that the first assembly line will make a1 boxes of type A1, then a2 boxes of type A2, etc., until it finishes with aN boxes of type AN. Similarly, the second assembly will make b1 toys of type B1, followed by b2 toys of type B2, etc., until it finishes with bM toys of type BM.
A toy can be matched with a box if and only if they have the same type number.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the largest number of boxed toys that you can send out to customers.
Limits
1 ≤ T ≤ 100.
1 ≤ ai, bi ≤ 10
16
.
1 ≤ Ai, Bi ≤ 100.
1 ≤ N, M ≤ 100.
Example
Input:
4
3 3
10 1 20 2 25 3
10 2 30 3 20 1
3 5
10 1 6 2 10 1
5 1 3 2 10 1 3 2 5 1
3 5
10 1 6 2 10 1
5 1 6 2 10 1 6 2 5 1
1 1
5000000 10
5000000 100
Output:
Case #1: 35
Case #2: 20
Case #3: 21
Case #4: 0 | 33,213 |
Matts Trip (MATT)
Matt finds himself in a desert with $N$ ($2 \leq N \leq 10$) oases, each of which may have food, water, and/or a palm tree. If oasis $i$ has food, then $F_i=1$ - otherwise, $F_i=0$. Similarly, $W_i=1$ if and only if oasis $i$ has water, and $P_i=1$ if and only if it has a palm tree. These 3 values are completely independent of one another.
Some pairs of these oases are connected by desert paths, which each take 1 hour to traverse. There are $M$ ($0 \leq M \leq 45$) such paths, with path $i$ connecting distinct oases $A_i$ and $B_i$ in both directions ($1 \leq A_i,B_i \leq N$). No pair of oases is directly connected by more than one path, and it's not guaranteed that all oases are connected by some system of paths.
Matt starts at an oasis $S$, and wants to end up at a different oasis $E$ ($1 \leq S,E \leq N$).
Both of these oases are quite nice - it's guaranteed that $F_S=W_S=P_S=F_E=W_E=P_E=1$.
Since he's in a hurry to get out of the desert, he wants to travel there in at most $H$ ($1 \leq H \leq 10^9$) hours.
However, he can only survive for up to $MF$ hours at a time without food, and up to $MW$ hours at a time without water ($1 \leq MF,MW \leq 4$). For example, if $MF=1$ and $MW=2$, then every single oasis he visits along the way must have food (as he would otherwise spend more than 1 hour without it), and he cannot visit 2 or more oases without water in a row.
Since Matt is a computer scientist, before actually going anywhere, he's interested in the number of different paths he can take that will get him from oasis $S$ to oasis $E$ alive in at most $H$ hours.
Note that there may be no such paths.
Being a computer scientist, he of course only cares about this number modulo ($10^9+7$).
Input
Line $1$: 7 integers, $N$, $M$, $H$, $S$, $E$, $MF$, and $MW$
Next $N$ lines: 3 integers, $F_i$, $W_i$, and $P_i$, for $i = 1..N$
Next $M$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..M$
Output
1 integer, the number of different valid paths, modulo ($10^9+7$)
Example 1
Input:
3 3 3 1 2 1 4
1 1 1
1 1 1
0 1 0
1 2
2 3
1 3
Output:
2
Explanation:
The two possible paths, described in terms of oases visited, are $1 \rightarrow 2$ and $1 \rightarrow 2 \rightarrow 1 \rightarrow 2$. Matt can never go to oasis 3, as it doesn't contain food, which he can't survive without for more than 1 hour. The path $1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 1 \rightarrow 2$ is not valid, as it would take 5 hours rather than at most 3.
Note that oasis 3 is the only oasis without a palm tree.
Example 2
Input:
5 5 3 3 2 3 2
1 0 0
1 1 1
1 1 1
0 0 1
0 1 0
1 2
1 3
1 4
3 4
4 2
Output:
2
Explanation:
The two possible paths are $3 \rightarrow 1 \rightarrow 2$ and $3 \rightarrow 4 \rightarrow 2$.
This time, oases 1 and 5 are lacking in palm trees. | 33,214 |
Good Travels (GOODA)
It's that time of year again - the best ACM-ICPC team of all time is off to the World Finals! Being the best, they realize that a good performance starts before the contest itself - in order to get into the perfect mindset, they must have as much fun on the trip to the contest site as possible!
The Team is interested in a network of N (2 <= N <= 10^6) cities (conveniently numbered 1..N), interconnected by M (1 <= M <= 10^6) one-way flights (similarly numbered 1..M). Their hometown is city S (1 <= S <= N), and the contest will take place in city E (1 <= E <= N, S != E). Flight i goes from city ai (1 <= ai <= N) to city bi (1 <= bi <= N, ai != bi), and no two flights connect the same pair of cities in the same direction. In general, no cities are guaranteed to be reachable from other cities by a sequence of flights. However, The Team of course knows that city E is reachable from city S - they're not about to break their streak of triumphant wins!
Now, each city i has a fun value, fi (0 <= fi <= 10^6), associated with it. Along their trip, The Team will take time to have fun at every city they visit, including the first and last. However, though they can visit a city multiple times (including cities S and E), or even take a certain flight multiple times, surely this gets boring quickly - therefore, any city's fun can only be had up to once.
The Team wants to determine the maximal amount of fun they can have on any sequence of flights that starts at city S and ends at city E. Naturally, every member on The Team is so intelligent that they've calculated this value in their heads (and are quite excited about it) - but can you?
Input
First line: 4 integers, N, M, S, and E
Next N lines: 1 integer, fi, for i = 1..N
Next M lines: 2 integers, ai and bi, for i = 1..M
Output
1 integer, the maximal amount of fun The Team can have on their trip.
Example
Input:
5 6 1 4
5
4
5
10
2
1 2
1 3
2 4
3 4
4 5
5 4
Output:
22
Explanation of Sample
The network of cities and flights looks like this (the fun values of cities are shown below them):
The optimal route that The Team can take goes through cities 1 → 3 → 4 → 5 → 4, yielding a total fun value of 5 + 5 + 10 + 2 + 0 = 22. | 33,215 |
Good Predictions (GOODB)
Having arrived at the ACM-ICPC contest site in a fun-filled mood, The Team continues their important pre-contest preparations. Specifically, every world-class team knows the importance of making predictions about their upcoming submissions.
The Team knows that they'll get plenty of AC (Accepted) submissions, and they find those quite boring by now. As such, they'll focus on their incorrect ones. From their vast experience, The Team knows that they'll only get exactly $N$ ($1 \leq N \leq 300$) submissions wrong throughout the upcoming contest - in fact, they predict that, of those, exactly $W$ ($0 \leq W \leq 100$) will get WA (Wrong Answer), $T$ ($0 \leq T \leq 100$) will get TLE (Time Limit Exceeded), and the remaining $R$ ($0 \leq R \leq 100$) will get RE (Runtime Error). Note that $W+T+R=N$.
Assuming that their predictions will certainly be correct, the members of The Team are wondering in how many ways that might occur. In other words, how many different ordered combinations of $N$ incorrect results (each being WA, TLE, or RE) exist which satisfy their predictions? Since The Team doesn't make many mistakes, surely you can calculate this value, right? However, since it can get quite large for you, compute it modulo ($10^9+7$).
Input
4 integers, $N$, $W$, $T$, and $R$
Output
1 integer, the number of valid ordered combinations of submission results, modulo ($10^9+7$).
Example
Input:
3 2 1 0
Output:
3
Explanation of Sample:
Out of 3 submissions, two are WA, while the third is TLE. The following 3 ordered combinations are then possible:
WA, WA, TLE
WA, TLE, WA
or
TLE, WA, WA
The answer is then $3$ modulo ($10^9+7$) = $3$. | 33,216 |
Good Strategy (GOODC)
The ACM-ICPC World Finals have begun! However, let's not be too hasty - even though The Team features three of the best coders to have ever coded, they know the importance of first determining
what
to code.
The contest features $N$ ($1 \leq N \leq 10^6$) problems (conveniently numbered $1..N$), and runs for $M$ ($1 \leq M \leq 10^6$) minutes. Every problem is associated with a distinct colour - and each time a team solves a problem, they receive a balloon of its corresponding colour, which is visible to all. Obviously, easier problems will be solved by more teams, and so more of their balloons will be floating around in the contest room. Additionally, The Team has found that earlier problems in the set tend to be easier. Therefore, given 2 problems $i$ and $j$, $i$ is considered easier than $j$ if there are either more $i$ balloons than $j$ balloons in the room, or there are an equal number of balloons and $i < j$.
At the start of the contest (at the 0th minute), there are no balloons in the room, of course. After that, during every minute $i$ (for $i=1..M$), problem $p_i$ ($1 \leq p_i \leq N$) is either solved by The Team (which will only happen if they have not solved it previously), or by some opposing team. The former possibility is represented by $t_i=1$, and the latter by $t_i=2$. In either case, a $p_i$ balloon is brought into the room. However, in the former case, The Team will no longer care about problem $p_i$ in the slightest.
At the end of every minute after the 0th one, the members of The Team want to get their bearings on what they should be working on (and what they should be staying away from). Specifically, out of problems that they haven't yet solved, they want to know what the single easiest and the single hardest problems are, given the information that can be gleaned from the balloons. These two values may be the same, if The Team has only one problem left to solve. If they're solved all of the problems already, they can instead commence the process of making distracting noises. Are you smart enough to figure out what The Team's strategy throughout the contest will be?
Input
First line: 2 integers, $N$ and $M$
Next $M$ lines: 2 integers, $t_i$ and $p_i$, for $i = 1..M$
Output
$M$ lines: Either 2 integers, the easiest followed by the hardest unsolved problem number after the first $i$ minutes, or the string "Make noise" if all problems have been solved by The Team, for $i = 1..M$.
Example
Input:
3 8
2 2
2 1
1 1
2 3
2 3
1 2
1 3
2 1
Output:
2 3
1 3
2 3
2 3
3 2
3 3
Make noise
Make noise
Explanation of Sample:
After the first minute, we've seen 1 balloon for problem 2, and 0 balloons for problems 1 and 3. Therefore, the easiest problem is 2, since it has the most balloons, and the hardest problem is 3, since it's the last problem with the least balloons.
After the second minute, the counts for the 3 problems are 1, 1, and 0. The easiest problem is now 1, since it's the first problem with the most balloons, while the hardest is still 3.
After the third minute, the counts for the 3 problems are 2, 1, and 0, but problem 1 has now been solved by The Team. The easiest remaining problem is 2, and the hardest is 3.
After the fourth minute, the counts for the 3 problems are 2 (solved), 1, and 1. The easiest unsolved problem is 2, and the hardest is 3.
After the fifth minute, the counts for the 3 problems are 2 (solved), 1, and 2. The easiest unsolved problem is 3, and the hardest is 2.
After the sixth minute, the counts for the 3 problems are 2 (solved), 2 (solved), and 2. The only unsolved problem is 3.
After the seventh and eighth minutes, all 3 problems have been solved by The Team, so noise should be made. | 33,217 |
Good Code (GOODD)
It's time for the members of The Team to do what they do best - coding! Faster than you can say "Dijkstra", they've already produced an elegant piece of work. The program has $N$ ($1 \leq N \leq 10^6$) lines of code (conveniently numbered $1..N$), and just one integer variable, $c$, which starts with a value of 0. The program starts executing at line 1, and every line $i$ contains one of the following:
"c++;" - The value of $c$ is incremented by 1. Then, if $i=N$, the program terminates - otherwise, the program moves to line $i+1$.
"x:" - This line contains the label $x$, where $x$ is an integer such that $1 \leq x \leq 10^6$. No value of $x$ will appear as a label more than once in the program. If $i=N$, the program terminates - otherwise, the program moves to line $i+1$.
"goto x;" - The program jumps to the single line that contains the label $x$, where $x$ is an integer such that $1 \leq x \leq 10^6$. It is guaranteed that, for every such line, the corresponding label will exist in the program.
Now, even though this program is glorious, its creators are wondering if it's quite correct. In particular, they know that $c$ should ideally reach a value of $M$ ($1 \leq M \leq 10^{12}$), but they're not sure when. If the program terminates with $c
Input
First line: 2 integers, $N$ and $M$
Next $N$ lines: The $i$th line of the program (as described above), for $i=1..N$
Output
Either 1 integer, the number of the line on which $c$ will first reach a value of $M$, or the string "WA" if the program terminates with $c
Example
Input:
12 4
c++;
goto 6;
18:
c++;
c++;
goto 2;
goto 6;
6:
goto 18;
2:
c++;
c++;
Output:
11
Explanation of Sample
The program will run through the following lines, and corresponding values of $c$:
Line 1 ("c++;"), $c=1$
Line 2 ("goto 6;"), $c=1$
Line 8 ("6:"), $c=1$
Line 9 ("goto 18;"), $c=1$
Line 3 ("18:"), $c=1$
Line 4 ("c++;"), $c=2$
Line 5 ("c++;"), $c=3$
Line 6 ("goto 2;"), $c=3$
Line 10 ("2:"), $c=3$
Line 11 ("c++;"), $c=4$
As can be seen, $c$ first achieves a value of $M=4$ on line 11. | 33,218 |
Good Debugging (GOODE)
Any good coder knows that writing a program is only half the battle - and each member of The Team is most certainly a good coder. Maybe you're not a good coder, though, and you're wondering what the other half is. Debugging, of course!
The Team has a program with $N$ ($1 \leq N \leq 10^6$) lines (conveniently numbered $1..N$) - and, unfortunately, every single line happens to initially have a bug in it. The programming language they're using will run the program from the start, line by line, and will always crash as soon as it encounters a total of $L$ ($1 \leq L \leq 10^6$) buggy lines.
The Team will make $M$ ($1 \leq M \leq 10^6$) attempts to debug the program. The $i$th attempt will consist of modifying every line in the inclusive range of lines $a_i..b_i$ ($1 \leq a \leq b \leq N$). In particular, these coders are so amazing that, every single time they modify a buggy line, it becomes perfect! However, every time they modify a perfect line, they instead introduce a bug into it. After every debugging attempt, The Team will run their new program, and observe how many lines of code it gets through before crashing. Sometimes, the program may even terminate successfully! The modified code will then carry over for future modifications.
Now, the members of The Team would like to know how their program will fare throughout the debugging session. Are your debugging skills good enough to figure that out?
Input
First line: 3 integers, $N$, $M$ and $L$
Next $M$ lines: $a_i$ and $b_i$, for $i=1..N$
Output
$M$ lines: Either 1 integer, the number of lines the program executes before crashing after the first $i$ modifications, or the string "AC?" if it doesn't crash at all, for $i=1..M$.
Example
Input:
6 4 2
2 4
4 6
1 1
1 2
Output:
5
4
AC?
2
Explanation of Sample:
The following table shows the status of each line of code after every modification, with newly-changed lines shown in bold font. Buggy lines represented by 1s, and correct ones by 0s.
After 1 modification, then, the program will encounter its second bug at line 5, at which point it will crash. Similarly, after 2 modifications, it will crash after 4 lines, and after 4 modifications, it will crash after just 2. After 3 modifications, however, it will not crash at all, as the program will contain only 1 bug at that point. | 33,219 |
Good Aim (GOODF)
The heated competition of the ACM-ICPC World Finals continues, and The Team is at the top of their game! Well, okay, maybe they're not actually doing so well, according to the scoreboard, yet. But they have a plan!
The contest is taking place in a huge room with a regular grid of desks. The columns and rows are each numbered $1..10^6$, and the desk in the $x$th column and $y$th row is considered to have coordinates ($x$,$y$). The Team is sitting at coordinates ($X$,$Y$). There are $N$ ($1 \leq N \leq 10^6$) opposing teams (conveniently numbered $1..N$), with team $i$ having $m_i$ ($1 \leq m_i \leq 10^6$) members, all sitting at coordinates ($x_i$,$y_i$). No desk is occupied by more than one team, and all other desks are empty.
Now, The Team is interested in removing some of the more dangerous opponents from the competition. To accomplish this, they have a number of water balloons at their disposal (after all, where in the contest rules does it say that water balloons are not allowed?). Always conservative, they would first like to answer $Q$ ($1 \leq Q \leq 10^6$) queries - for the $i$th query, how many balloons it would theoretically take to take out all of the members of team $q_i$?
In order to do any real damage, the water balloons will of course have to be thrown extremely hard - in fact, in a perfectly straight line, and not over any obstacles besides empty desks. This means that, if team $j$ lies exactly on the line segment from The Team to team $i$, then every member of team $j$ must be dispatched before any members of team $i$ can be hit. It takes one balloon to knock one person out (the members of The Team have received plenty of training, so they're not about to miss a throw). Note that these queries are all only theoretical (for the moment) - so each should be answered assuming that all teams are still untouched.
The members of The Team will need to carefully choose with opponents to take out, based on how well they're doing and how many balloons it would take, so they're already answered all of their queries in their heads. Maybe, if you can answer them as well, you can also adopt such techniques in the future...
Input
First line: 4 integers, $N$, $Q$, $X$, and $Y$
Next $N$ lines: 3 integers, $x_i$, $y_i$, and $m_i$, for $i = 1..N$
Next $Q$ lines: 1 integer, $t_i$, for $i = 1..Q$
Output
$Q$ lines: 1 integer, the number of balloons that would be required to take out team $t_i$, for $i = 1..Q$.
Example
Input:
6 6 3 2
5 6 3
2 1 5
4 4 2
4 3 1
5 4 2
7 6 1
6
5
4
3
2
1
Output:
4
3
1
2
5
5
Explanation of Sample:
The following grid shows the positions of the $N$ opposing teams (marked with their numbers), as well as The Team (marked with a "T"). The line segments represent direct lines of sight to the opponents.
As can be seen, team 6 is blocked by teams 4 and 5. Therefore, taking them out would require $1+2+1=4$ balloons in total. Similarly, team 5 is blocked by team 4, and requires $1+2=3$ balloons. Teams 4, 3, and 2 are not blocked by any others, and so only require 1, 2, and 5 balloons, respectively. Finally, team 1 is blocked by team 3, and would require $2+3=5$ balloons to dispose of. | 33,220 |
Good Inflation (GOODG)
The competition is drawing to a close, and The Team could really use another balloon to help them come out on top...good thing they're no chumps, and thought of this in advance! Before the contest started, they instructed an accomplice to go to the local balloon shop, buy an extra balloon, and deliver it to them at the conclusion of the event. It is true that their balloons then won't match up with the scoreboard's record of which problems they've solved - but, in the end, it's the balloons that count! In fact, The Team knows that, the larger their extra balloon, the more their opponents (and the judges) will be intimidated. They're not the best ACM-ICPC team in the world for nothing!
However, this balloon shop is rather strange. The accomplice is given an empty balloon (a balloon with size 0), and told that he can tie it closed and keep it after exactly $N$ ($1 \leq N \leq 10^6$) minutes. In the meantime, during each minute, an inflation offer is available. If offer $i$ is taken, then, at the start of the $i$th minute, the balloon's size will be increased by $a_i$ ($0 \leq a_i \leq 10^6$). However, since the balloon cannot be closed until the end, its air will leak out at a constant rate, which depends on the gas that was used - in particular, its size will immediately start to decrease at a rate of $d_i$ ($0 \leq d_i \leq 10^6$) per minute, until either another offer is taken, or the balloon deflates completely (its size can never become negative, of course).
The Team will not be happy if they don't receive the largest balloon possible. Unfortunately, their accomplice happens to be...you. Can you figure out the maximal size that the balloon can have at the start of minute $N+1$, before it's too late?
Input
First line: 1 integer, $N$
Next $N$ lines: 2 integers, $a_i$ and $d_i$, for $i=1..N$
Output
1 integer, the maximal size which the balloon can have at the start of minute $N+1$.
Example
Input:
5
2 3
10 2
0 1
5 4
1 10
Output:
5
Explanation of Sample:
The best option is to take only the offers at minutes 2 and 3. At the start of minute 2, the balloon will be inflated to size 10, and will deflate to size 8 by the start of minute 3. At that point, the balloon's size will not change, but its deflation rate will change to 1. As a result, by the start of minute 6, its size will be 5.
Note that, if the offer at minute 1 is additionally taken, the balloon will simply be inflated to size 2 before deflating back to size 0 by the start of minute 2 - therefore, this will not change the outcome.
Also note that, if the offer at minute 4 is additionally taken, the balloon will inflate to size 12 at the start of minute 4, but its deflation rate of 4 will result in a size of 4 at the start of minute 6, which is not optimal. | 33,221 |
Good Celebration (GOODH)
The ACM-ICPC World Finals are over! Which team came out on top? Why, only our favourite team - everyone's favourite team - the most deserving, lovable, courteous, powerful, flawless, successful team that has ever existed. Who else?
It's time to celebrate, and what better way is there to celebrate than by eating cake? The contest organizers have bought $N$ ($1 \leq N \leq 200$) cakes (conveniently numbered $1..N$) - however, ever generous, The Team will only eat cake 1, leaving the rest for the other, inferior teams. They
will
need their cake to be as tasty as possible, though. To help with this, $M$ ($0 \leq M \leq 200$) globs of icing are available, which will be distributed among the cakes. Icing is always used in whole globs.
The cakes are arranged in a somewhat strange way - piled on top of one another. Cake 1 is directly on top of a table, while every other cake $i$ (for $i=2..N$) is directly on top of cake $c_i$. $c_1$ is considered to have a value of 0. Note that there may be multiple cakes on top of a single cake, and that the entire structure obeys the laws of physics (no cake is on top of itself, and no cakes are floating).
Now, the tastiness of any cake $i$ is determined by the formula $b_i + m_i(x_i + y_i)$. $b_i$ ($0 \leq b_i \leq 100$) and $m_i$ ($0 \leq m_i \leq 100$) are simply properties of cake $i$, which depend on its size, shape, weight, temperature, fluffiness, and so on. $x_i$ is the number of globs of icing that are chosen to be applied to cake $i$. If there are no cakes on top of cake $i$, $y_i=0$ - otherwise, $y_i$ is the minimal tastiness of any cake directly on top of cake $i$. No cake will ever be capable of achieving a tastiness value larger than $2^{60}$, no matter how the icing is distributed.
The members of The Team have already, of course, determined how the available icing could be optimally applied to the mountain of cakes to maximize the tastiness of their cake (cake 1). However, the contest organizers are the ones who will actually be distributing the icing, and they had better hope they get it right! Can you help them determine how tasty cake 1 should be? You don't want to know what The Team will do if their celebration isn't perfect...
Input
First line: 2 integers, $N$ and $M$
Next $N$ lines: 3 integers, $c_i$, $b_i$, and $m_i$, for $i=1..N$
Output
1 integer, the maximal tastiness of cake 1, after all of the icing has been used
Example
Input:
3 2
0 5 1
1 3 4
1 2 6
Output:
12
Explanation of Sample:
The optimal icing distribution is 1 glob each on cakes 2 and 3. This gives cake 2 a tastiness of $3+4(1+0)=7$, and cake 3 a tastiness of $2+6(1+0)=8$. Since both of these cakes are on top of cake 1, it then has a tastiness of $5+1(0+min\{7,8\})=12$. No other icing distribution yields a higher tastiness for cake 1. | 33,222 |
Zig when you zag (ZIGZAG2)
We say that a sequence of numbers x(1), x(2) ... x(k) is zigzag if no three of its consecutive elements create a non-increasing or non-decreasing sequence. More precisely, for all i=1, 2 ... k-2 either x(i+1) < x(i), x(i+2) or x(i+1) > x(i), x(i+2).
You are given two sequences of numbers a(1), a(2) ... a(n) and b(1), b(2) ... b(m). The problem is to compute the length of their longest common zigzag subsequence. In other words, you're going to delete elements from the two sequences so that they are equal, and so that they're a zigzag sequence. If the minimum number of elements required to do this is k then your answer is m+n-2k.
Input
There is a single integer t (t ≤ 100) on the first line of input. Then t test cases follow. Each of them consists of two lines. The first line contains the length of the first sequence n (1 ≤ n ≤ 2000) and n integers a(1), a(2) ... a(n). The second line contains the length of the second sequence m (1 ≤ m ≤ 2000) and m integers b(1), b(2) ... b(m). All a(i) and b(i) are from [-10
9
, 10
9
]. (REPEAT: the first number on the line is not part of the sequence, it's the length of the sequence.)
Output
For each test case output one line containing the length of the longest common zigzag subsequence of a and b.
Example
Input:
2
5 1 2 5 4 3
5 4 1 2 5 3
3 1 2 1
2 1 1
Output:
3
2 | 33,223 |
King Graffs Defense (GRAFFDEF)
King Graff, the ruler of the land of Feerie, has a problem - his nation is under attack! Luckily, he has an army at his disposal, composed of a whopping $S$ soldiers (where $S = 2$).
Feerie consists of $N$ ($1 \leq N \leq 100,000$) towns (numbered $1..N$), and $M$ ($1 \leq M \leq 500,000$) roads. The $i$th road runs between distinct towns $A_i$ and $B_i$, in both directions. No pair of towns is directly connected by more than one road, but every pair of towns is connected by at least one path of connected roads. King Graff would like to position his two soldiers in two different towns to prepare for the impending assault - however, since he's not much of a strategist, he'll choose the towns at complete random.
Graff's only real concern is with his enemies using a divide-and-conquer strategy. His soldiers will be susceptible to this type of attack if there exists any single road that, if blocked, will prevent them from reaching each other by any system of connected roads. As the royal computer scientist, your job is to determine the probability that King Graff will be defeated.
Input
First line: 2 integers, $N$ and $M$
Next $M$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..M$
Output
1 real number (rounded to 5 decimal places), the probability that the two towns chosen by Graff can be disconnected by the removal of any single road
Example
Input:
4 4
1 2
1 3
2 4
4 1
Output:
0.50000
Explanation of Sample:
The map of Feerie is illustrated below:
King Graff can make 6 possible choices as to where to place his soldiers, and three of those (the three with one of the soldiers being at town 3) result in defeat (if the road between towns 1 and 3 is destroyed). The probability of failure is then $3/6 = 0.5$. | 33,224 |
King Graffs Tolls (GRAFFTOL)
King Graff, the ruler of the land of Feerie, feels that he is not quite rich enough. As such, he would like to impose travel tolls on his people! After all, why should they get to walk around his kingdom for free?
Feerie consists of $N$ ($1 \leq N \leq 10^5$) towns (numbered $1..N$), and $N-1$ roads. The $i$th road runs between distinct towns $A_i$ and $B_i$, in both directions. Every pair of towns is connected by exactly one path of connected roads. Currently, all travel is free, but King Graff is interested in charging for passage through certain towns.
He is planning to have a meeting with the royal computer scientist - that would be you. The meeting will last $M$ ($1 \leq M \leq 10^5$) minutes, and in the $i$th minute, one of two things will occur, described by $T_i$. If $T_i=$ "T", Graff will proclaim that town $X_i$ shall henceforth cost $Y_i$ ($0 \leq Y_i \leq 10^9$) dollars to pass through, and you'll update the map accordingly. Otherwise, if $T_i=$ "Q", he will ask you how much a trip from town $X_i$ to a different town $Y_i$ would currently cost a commoner, in order to gauge the effectiveness of his tolls - and you had better answer quickly! Note that neither the starting nor the ending town's tolls are included in a trip's cost, as they are not passed through. Note also that a town's toll may be modified by Graff mutiple times throughout the meeting, in which case the most recent modification at any point will stand.
Input
First line: 1 integer, $N$
Next $N-1$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..N-1$
Next line: 1 integer, $M$
Next $M$ lines: 1 character, $T_i$, and 2 integers, $X_i$ and $Y_i$, for $i = 1..M$
Output
$X$ lines (where $X$ is the number of questions asked by King Graff): 1 integer, the cost of the $i$th trip asked for (in dollars), for $i = 1..X$
Example
Input:
4
1 3
2 3
4 3
6
Q 1 4
T 3 5
Q 4 2
Q 3 1
T 3 1
Q 1 2
Output:
0
5
0
1
Explanation of Sample:
The map of Feerie is illustrated below:
The first trip asked for by King Graff goes through towns $1 \rightarrow 3 \rightarrow 4$. Since town 3 has no toll at that point, the trip's cost is 0.
The second trip goes through towns $4 \rightarrow 3 \rightarrow 2$ and has a cost of 5, due to the new toll on town 3.
The third trip goes through towns $3 \rightarrow 1$, passing through no towns and so costing nothing.
The final trip goes through towns $1 \rightarrow 3 \rightarrow 2$ and costs only 1, as town 3's toll is reduced by then. | 33,225 |
King Graffs Trip (GRAFFTRI)
King Graff, the ruler of the land of Feerie, is going on a trip through his realm! He would like to give his people a chance to see their great king amongst them, almost as if he too were a petty commoner with no future.
Feerie consists of $N$ ($1 \leq N \leq 10^4$) towns (numbered $1..N$), and $M$ ($1 \leq M \leq 10^5$) roads. The $i$th road runs from town $A_i$ to a different town $B_i$ (and can only be travelled in that one direction), and takes $T_i$ ($1 \leq T_i \leq 10^9$) minutes to traverse. No pair of towns is directly connected by more than one road in the same direction. King Graff will start his trip at town $X$, and would like to end at a different town $Y$. Furthermore, since he has better things to do, he would like to complete it in at most $L$ ($1 \leq L \leq 10^{15}$) minutes.
However, Graff does not like to go long without being worshipped, and the only proper place to do this is in a shrine built to him. $S$ ($1 \leq S \leq 100$) distinct towns contain such shrines - the $i$th shrine is in town $H_i$. He would like to minimize the longest continuous stretch of time spent during the trip without passing through any shrines. As the royal computer scientist, your job is to determine the length of this stretch, or break the news to your king that the trip cannot be completed in time. Note that the trip may be impossible to complete in any amount of time, if town $Y$ is not reachable from town $X$ by any path of connected roads.
Input
First line: 5 integers, $N$, $M$, $X$, $Y$, and $L$
Next $M$ lines: 3 integers, $A_i$, $B_i$, and $T_i$, for $i = 1..M$
Next line: 1 integer, $S$
Next $S$ lines: 1 integer, $H_i$, for $i = 1..S$
Output
Line 1: 1 integer - the minimum value for the longest continuous stretch of travel time spent away from shrines (in minutes), or -1 if the trip cannot be completed in at most $L$ minutes
Example
Input:
5 7 2 3 7
2 3 5
3 2 1
2 1 4
1 3 3
2 4 3
4 5 2
5 3 3
3
1
4
5
Output:
4
Explanation of Sample:
The map of Feerie is illustrated below:
The optimal route goes through towns $2 \rightarrow 1 \rightarrow 3$, taking 7 minutes with at most 4 minutes spent away from any shrines. The route $2 \rightarrow 3$ is shorter (taking 5 minutes), but has a longer continuous time away from shrines (5). The route $2 \rightarrow 4 \rightarrow 5 \rightarrow 3$ has a shorter such value (3), but takes longer than 7 minutes in total (8) and as such is not allowed. | 33,226 |
abdou set (KIMO1)
Abdou
has a set of unique positive integers. He wants to add several (possibly none) new positive integers to this set, such that when the set is sorted, for every two consecutive numbers X, Y abs(X%M-Y%M) = 1 . Your task is to calculate the smallest possible count of new numbers, with which he can achieve that.
Input
The first line contains T, the number of test cases. It is followed by 2*T lines, two lines per test case. The first line contains two positive integers M and N. The second line contains N integers.
1 <= T <= 5000.
1 <= M <= 10^5.
2 <= N <= 50.
1 <= every integer in the set <= 10^6.
Output
For test case print a single integer in a separate line: the smallest possible count of new numbers, with which he can complete the set or -1 if no solution exists.
Example
Input:
5
2 3
2 10 20
10 2
10 20
10 6
11 19 5 30 40 100
1 2
1 9999
15 3
4218 15210 1426
Output:
2
1
-1
-1
3
Explanation
In the first test case we can add 3 and 13 to the given set to achieve Abdou's goal. | 33,227 |
Pyramidal Constructions (PIRACON)
Humberto is a great Egyptian architect. In Egypt pyramid sculptural constructions were as common as ornaments. Pharaoh has asked Humberto to build N pyramids throughout Egypt. Humberto is very stingy when it comes to construction costs, so he always buys the exact necessary number of materials needed to complete his work.
Tural Pyramids are built using smallest pyramids of "level 1", that are used as building blocks for higher levels. Stacking pyramids of "level 1" to create higher-level structures, leave gaps. Special parts, called "Tringus", are used to cover these gaps. They are of triangular shape, designed by Humberto to perfectly fill the gaps on piramid sides.
For example, a pyramid of "Level 2" is constructed as follows: We are using a total of 6 pyramids of "level 1" (see the picture above). That leaves 4 gaps at the sides and we need 4 "Tringus" fo fill them. In total 10 pieces.
Humberto asks us to help to calculate the total number and "Tringus" number of pieces needed for a pyramid of level K.
Input
First line contains integer T, number of test cases. Following N lines, each containing an integer K, the level of the piramid.
Output
You must print "Pyramid E. Nro# i: ", followed by the total number of parts used (both pyramids of "level 1" and "Tringus"). In the next line print "Tringus: ", followed by the number of "Tringus" used.
Example
Input:
2
1
4
Output:
Pyramid E. Nro# 1: 1
Tringus: 0
Pyramid E. Nro# 2: 68
Tringus: 24
Constraints
1<= T <= 10^4
1<= K <= 10^6 | 33,228 |
Subsequence (SUBSN)
A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example “abd” is a subsequence of “abcdef”. - Wikipedia.
Your task in this problem is to decide if a given string is a subsequence of another string or not?
Easy?
Input
The first line of input will be the number of test cases. Each test case will start with a line contains a string S, S will have letters from 'a' to 'z' and the length of S ≤ 100,000. This line will be followed by a number Q which is the number of queries you have to answer for the given string S, 1 ≤ Q ≤ 1000. Each of the next Q lines will contain a string T, T will have letter from 'a' to 'z' and the length of T ≤ 200. For each T you have to decide if T is a subsequence of S or not.
Output
For each test case print Q + 1 lines, The first line will have “Case C:” without quotes where C is the case number starting with 1. The next Q lines will have either “YES” or “NO” if the cross-ponding T is a subsequence of S or not respectively.
Example
Input:
1
abcdef
3
abd
adb
af
Output:
Case 1:
YES
NO
YES
Editors note:
Strings in the input can be empty. Read data carefully to avoid issues. There should be no extra whitespaces of course except '\n'. | 33,229 |
Princess Farida (FARIDA)
Once upon time there was a cute princess called Farida living in a castle with her father, mother and uncle. On the way to the castle there lived many monsters. Each one of them had some gold coins. Although they are monsters they will not hurt. Instead they will give you the gold coins, but if and only if you didn't take any coins from the monster directly before the current one. To marry princess Farida you have to pass all the monsters and collect as many coins as possible. Given the number of gold coins each monster has, calculate the maximum number of coins you can collect on your way to the castle.
Input
The first line of input contains the number of test cases. Each test case starts with a number N, the number of monsters, 0 ≤ N ≤ 10
4
. The next line will have N numbers, number of coins each monster has, 0 ≤ The number of coins with each monster ≤ 10
9
. Monsters described in the order they are encountered on the way to the castle.
Output
For each test case print “
Case C: X
” without quotes. C is the case number, starting with 1. X is the maximum number of coins you can collect.
Example
Input:
2
5
1 2 3 4 5
1
10
Output:
Case 1: 9
Case 2: 10 | 33,230 |
Lowest Common Ancestor (LCA)
A tree is an undirected graph in which any two vertices are connected by exactly one simple path. In other words, any connected graph without cycles is a tree. - Wikipedia
The lowest common ancestor (LCA) is a concept in graph theory and computer science. Let T be a rooted tree with N nodes. The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself). - Wikipedia
Your task in this problem is to find the LCA of any two given nodes v and w in a given tree T.
For example the LCA of nodes 9 and 12 in this tree is the node number 3.
Input
The first line of input will be the number of test cases. Each test case will start with a number N the number of nodes in the tree, 1 ≤ N ≤ 1,000. Nodes are numbered from 1 to N. The next N lines each one will start with a number M the number of child nodes of the Nth node, 0 ≤ M ≤ 999 followed by M numbers the child nodes of the Nth node. The next line will be a number Q the number of queries you have to answer for the given tree T, 1 ≤ Q ≤ 1000. The next Q lines each one will have two number v and w in which you have to find the LCA of v and w in T, 1 ≤ v, w ≤ 1,000.
Input will guarantee that there is only one root and no cycles.
Output
For each test case print Q + 1 lines, The first line will have “Case C:” without quotes where C is the case number starting with 1. The next Q lines should be the LCA of the given v and w respectively.
Example
Input:
1
7
3 2 3 4
0
3 5 6 7
0
0
0
0
2
5 7
2 7
Output:
Case 1:
3
1 | 33,231 |
Cactus (CAC)
In the mathematical field of graph theory, a spanning tree T of a connected, undirected graph
G is a tree composed of all the vertices and some (or perhaps all) of the edges of G. Informally,
a spanning tree of G is a selection of edges of G that form a tree spanning every vertex. That is,
every vertex lies in the tree, but no cycles (or loops) are formed. On the other hand, every
bridge of G must belong to T (a bridge is an edge whose deletion increases the number of
connected components).
A spanning tree of a connected graph G can also be defined as a maximal set of edges of G that
contains no cycle, or as a minimal set of edges that connect all vertices. - Wikipedia
In graph theory, a cactus (sometimes called a cactus tree) is a connected graph in which any
two simple cycles have at most one vertex in common. Equivalently, every edge in such a graph
belongs to at most one simple cycle. Equivalently, every block (maximal subgraph without a
cut-vertex) is an edge or a cycle. - Wikipedia
In the mathematical field of graph theory, a spanning tree T of a connected, undirected graph G is a tree composed of all the vertices and some (or perhaps all) of the edges of G. Informally, a spanning tree of G is a selection of edges of G that form a tree spanning every vertex. That is, every vertex lies in the tree, but no cycles (or loops) are formed. On the other hand, every bridge of G must belong to T (a bridge is an edge whose deletion increases the number of connected components).
A spanning tree of a connected graph G can also be defined as a maximal set of edges of G that contains no cycle, or as a minimal set of edges that connect all vertices. - Wikipedia
In graph theory, a cactus (sometimes called a cactus tree) is a connected graph in which any two simple cycles have at most one vertex in common. Equivalently, every edge in such a graph belongs to at most one simple cycle. Equivalently, every block (maximal subgraph without a cut-vertex) is an edge or a cycle. - Wikipedia
cactus graph
Your task in this problem is to count the number of ways you can convert a cactus graph to a spanning tree.
Input
The first line of input will be the number of test cases. Each test case will start with a two numbers N and E where N is the number of vertices of the cactus graph, vertices are numbered from 1 to N, 3 <= N <= 81 and E is the number of edges in the graph, 2 <= E <= 120. The next E lines each one will have two numbers v and w and that means there is an edge between vertix v and w.
Output
For each test case print “Case C: X” without quotes where C is the case number starting with 1 and X is the number of ways you can convert the given cactus graph to a spanning tree.
Example
Input:
2
3 3
1 2
2 3
1 3
5 5
1 2
2 3
2 4
3 4
4 5
Output:
Case 1: 3
Case 2: 3 | 33,232 |
Dynamically-Rooted Tree (DRTREE)
You are given a rooted tree with N nodes, numbered from 1 to N. Initially node 1 is the root. Each node i has a weight W[i]. You have to perform two types of operations:
"S a"
- Find the sum of weights of node
a
's sub-tree nodes (including node
a
).
"R a"
- Change root of the tree to
a
.
Input
Line 1:
N (1 <= N <= 10
5
), number of nodes.
Line 2:
N space-separated integers, weights of nodes from 1 to N.
i
'th integer is W[i] (1 <= W[i] <= 10
9
).
Line 3:
N-1 space-separated integers,
i
'th integer is the parent of node
i+1
.
Line 4:
Q, the number of operations (1 <= Q <= 10
5
).
Lines 5 .. 5+Q-1:
Every line contains a space separated character and an integer. Character describes the type of the operation, and integer is the node number.
Output
For each operation of type 'S', output the operations result in a separate line.
Example
Input:
5
2 1 1 1 2
1 1 2 2
3
S 2
R 2
S 1
Output:
4
3 | 33,233 |
Reindeer Games (SANTA1)
With the presents all crafted and packed into Santa's sack, it's almost time for his annual trip across the world, spreading cheer to all! However, he's first taking the time to experiment with various combinations of reindeer to pull his sleigh. For a successful journey, they'll have to work productively!
Every reindeer has a unique name (a string of up to 20 case-sensitive letters), as well as a seniority and a productivity value (both positive integers no larger than $10^6$). When a group of reindeer is chosen to pull the sleigh, they line up in single file, always in descending order of seniority from the front. If multiple reindeer have the same seniority, they line up in descending order of productivity within themselves (no two reindeer have both the same seniority and the same productivity). The productivity of a pair of adjacent reindeer in the lineup is the product of their individual productivity values, and the total productivity of the lineup is the sum of all such productivities. The total productivity of a group of fewer than 2 reindeer is 0.
Starting with an empty group of reindeer, Santa will perform $M$ ($1 \leq M \leq 10^5$) modifications. The $i$th modification will involve the reindeer with name $N_i$. If $A_i=$ 'A', then this reindeer will be added to the lineup (in its correct spot) - in this case, its seniority and productivity values, $S_i$ and $P_i$, will be given. Otherwise, if $A_i=$ 'R', then this reindeer will be removed from the lineup. Each reindeer will only be added once, and will only be removed if it's currently in the lineup.
To track which combinations of reindeer are more effective than others, Santa would like you to calculate the total productivity of the lineup after every modification made to it. Quickly, now, Christmas won't wait!
Input
First line: $M$
Next $M$ lines: $A_i$ and $N_i$, followed by $S_i$ and $P_i$ if $A_i=$ 'A', for $i = 1 .. M$
Output
$M$ lines: The total productivity of the reindeer lineup after every modification
Example
Input:
5
A Dancer 5 2
A Prancer 3 8
A Vixen 10 9
R Dancer
A Rudolph 3 1
Output:
0
16
34
72
80
Explanation of Sample:
After the first modification, the lineup consists of just Dancer, and so the total productivity is $0$.
After the second modification, Prancer is standing behind Dancer. Their productivity is $2 \cdot 8 = 16$.
After the third modification, we have Vixen, followed by Dancer, followed by Prancer. The productivity of Vixen and Dancer is $18$, while that of Dancer and Prancer is again $16$. Thus, the total productivity is $34$.
After the fourth modification, the lineup consists of only Vixen and Prancer, with productivity $72$.
Finally, after the fifth modification, Rudolph is behind Prancer, with this pair of reindeer contributing $8$ productivity, for a total of $80$. | 33,234 |
Travelling Santa (SANTA2)
At last, Santa is on his way! He's got a number of presents to deliver to various households, and he won't stop until he's disposed of them all. However, each present is only suitable for one gender - for example, men might enjoy such things as baseball bats, football helmets, and certain adult reading material, while women would prefer make-up, knitting needles, and certain other adult reading material.
At the moment, Santa is in a neighbourhood with $H$ ($1 \leq H \leq 50$) houses (numbered $1..H$), connected by $R$ ($1 \leq R \leq 10^{4}$) roads. The family living in house $i$ includes $M_i$ ($0 \leq M_i \leq 10$) males and $F_i$ ($0 \leq F_i \leq 10$) females. The $i$th road runs between distinct houses $A_i$ and $B_i$, and can be travelled in either direction. No pair of houses is directly connected by more than one road.
Santa starts at house $1$, carrying $M_S$ ($0 \leq M_S \leq 50$) male-appropriate and $F_S$ ($0 \leq F_S \leq 50$) female-appropriate presents. He then repeats the following process until he's out of gifts. First, he moves randomly to an adjacent house (a house reachable by taking one road) - it's guaranteed that there will be at least one such house. If he currently has $m$ male-appropriate and $f$ female-appropriate presents, his probability of moving to adjacent house $i$ is proportional to the value of $M_i m + F_i f$. Of course, the probabilities for all adjacent houses must add up to $1$. Note that if this value is $0$ for all adjacent houses, then Santa will move to any of them with equal probability. After reaching the new house, he delivers a male present to it with probability $\frac{m}{m+f}$, and a female present otherwise.
Wanting to plan ahead to leaving this neighbourhood, Santa is curious as to where he'll end up. He'd like you to calculate the probability of him being at each of the $H$ houses when he runs out of presents.
Input
First line: $H$ and $R$
Next $H$ lines: $M_i$ and $F_i$, for $i = 1..H$
Next $R$ lines: $A_i$ and $B_i$, for $i = 1..R$
Next line: $M_S$ and $F_S$
Output
$H$ lines: The probability of Santa finishing his present-delivering process at house $i$, rounded off to 6 decimal places, for $i = 1..H$
Example
Input:
4 3
1 2
2 1
1 1
4 0
1 2
2 4
3 1
1 1
Output:
0.760000
0.000000
0.000000
0.240000
Explanation of Sample:
The neighbourhood looks as follows:
House $1$ is adjacent to houses $2$ and $3$. The probability of Santa moving to house $2$ is proportional to $2 \cdot 1 + 1 \cdot 1 = 3$, while the probability of him moving to house $3$ is proportional to $1 \cdot 1 + 1 \cdot 1 = 2$. Therefore, he will move to house $2$ with probability $\frac{3}{5}$, and to house $3$ with probability $\frac{2}{5}$. If he moves to house $3$, then, regardless of which present he delivers, he will be guaranteed to move back to house $1$ next, where he will deliver the remaining present.
Otherwise, if he moves to house $2$ at first, then he will proceed to deliver a male-appropriate present there with probability $\frac{1}{1+1} = \frac{1}{2}$, and a female-appropriate one also with probability $\frac{1}{2}$. In the former case, he will then have just 1 female present remaining, so he will move on to house $4$ with probability $0$, and back to house $1$ with probability $1$. Otherwise, he will have 1 male present remaining, and will move on to house $4$ with probability $\frac{4}{5}$, and back to house $1$ with probability $\frac{1}{5}$. In any case, he will then deliver his second present and be done.
Editors note:
You can deliver more male or female presents to a house, than the number of given gender inhabitants. Even if that number would be zero, you could still drop given type of presents. You only need to follow the formulas in the problem description. | 33,235 |
Breaking and Entering (SANTA3)
Santa's favourite part of Christmas is, of course, entering people's houses through their fireplaces at night and leaving them presents. On this occasion, he's visiting a house which can be modeled as a rectangular grid of cells, with $R$ ($1 \leq R \leq 100$) rows and $C$ ($1 \leq C \leq 100$) columns. Each cell is either empty (represented by a '.'), contains a wall ('#'), contains a fireplace ('F'), contains a stocking of a certain size ('1'..'9'), or is empty but initially contains a dog facing in a certain direction (with up represented by '^', right by '>', down by 'v', and left by '<'). Exactly one cell contains a fireplace, and this is where Santa begins his business.
Based on the layout of the house, Santa has devised a plan of action in advance. He will enter carrying $P$ ($1 \leq P \leq 10^9$) presents, and will proceed to execute $M$ ($1 \leq M \leq 1000$) moves in order, one each second. Each move consists of moving one cell up (represented by a 'U'), right ('R'), down ('D'), or left ('L'). However, Santa cannot walk through walls, so if he would move outside the grid, or if the cell that he would move into contains a wall, he stays put for the second.
Each second, just as Santa is making his move, all of the dogs in the house also move simultaneously. Each dog moves forward one cell in the direction that it's facing, if that cell is within the grid and is empty (ignoring other dogs or Santa). Otherwise, it rotates clockwise by 90 degrees. Note that dogs don't interfere with one another in any way, and at various points in time there may be multiple dogs in a single cell.
Now, at the end of the second, if Santa finds himself in a cell with a stocking, he deposits a single present in it, if possible. In particular, he must be carrying at least one present, and the stocking must not have already been stuffed with a number of gifts equal to its capacity. Otherwise, if Santa is in the cell containing the fireplace, he immediately exits the house
if
he has no presents left, and/or he has already placed at least one present into every stocking in the house. Finally, if Santa finds himself in the same cell as one or more dogs, each such dog in turn steals half of his remaining presents, rounded up.
Before executing his brilliant plan, Santa would like to know how well his excursion will actually go. He'd like you to make a copy of the grid representing the house, but with every cell containing a stocking labelled with a digit ('0'..'9') representing how many presents that stocking will contain in the end, and with every other cell represented by just a '.'. He'd also like to know where in the house he'll end up.
Input
First line: $R$ and $C$
Next $R$ lines: $C$ characters, representing the $i$th row of the grid as described above, for $i=1..R$
Next line: $M$ and $P$
Next line: $M$ characters, representing Santa's moves
Output
$R$ lines: $C$ characters, representing the distribution of presents in the $i$th row of the grid as described above, for $i=1..R$
Next line: The row and column of the last cell which Santa will visit
Example
Input:
5 3
.1.
#F3
#9.
..1
..<
10 4
RRDDDULUUU
Output:
.0.
..2
.0.
..1
...
2 2
Explanation of Sample:
After his first move, Santa ends up at coordinates (2,3) (the 3rd cell in the 2nd row), and deposits one present there. During his second move, he stays in that cell due to hitting the right wall of the house, and so he deposits another gift in the stocking.
After 2 more seconds, he reaches the stocking at coordinates (4,3), and fills it up with a present. He returns to this cell 2 seconds later, but cannot put his last gift in the stocking because it's full.
On his next move, Santa encounters a dog at coordinates (4,2). Before this, the dog had moved left to (5,1), rotated, moved up to (4,1), rotated, and moved to (4,2) after 6 seconds - when Santa arrives after 7 seconds, the dog is still in this cell, rotating to face downwards. As such, Santa loses his only remaining present to it.
He next moves up to coordinates (3,2), but cannot deposit any presents in the stocking there because he has none. Finally, he moves up to the fireplace at coordinates (2,2), at which point he exits the house without ever making the final move up to (1,2). | 33,236 |
HELPER (HELPER)
It's unbelievable, but an exam period has started at the OhWord University. It's even more unbelievable, that Valera got all the tests before the exam period for excellent work during the term. As now he's free, he wants to earn money by solving problems for his groupmates. He's made a
list
of subjects that he can help with. Having spoken with
n
of his groupmates, Valera found out the following information about them: what subject each of them passes, time of the exam and sum of money that each person is ready to pay for Valera's help.
Having this data, Valera's decided to draw up a timetable, according to which he will solve problems for his groupmates. For sure, Valera can't solve problems round the clock, that's why he's found for himself an optimum order of day and plans to stick to it during the whole exam period. Valera assigned time segments for sleep, breakfast, lunch and dinner. The rest of the time he can work.
Obviously, Valera can help a student with some subject, only if this subject is on the
list
. It so happens, that all the students, to whom Valera spoke, have different, but one-type problems. Valera can solve any problem of subject
list
i
in
t
i
minutes.
Moreover, if Valera starts working at some problem, he can break off only for sleep or meals, but he can't start a new problem, not having finished the current one. Having solved the problem, Valera can send it instantly to the corresponding student via the Internet.
If this student's exam hasn't started yet, he can make a crib, use it to pass the exam successfully, and pay Valera the promised sum. Since Valera has little time, he asks you to write a program that finds the order of solving problems, which can bring Valera maximum profit.
Input
The first line contains integers
m
,
n
,
k
(1 ≤
m
,
n
≤ 100, 1 ≤
k
≤ 30) — amount of subjects on the
list
, amount of Valera's potential employers and the duration of the exam period in days.
The following
m
lines contain the names of subjects
list
i
(
list
i
is a non-empty string of at most 32 characters, consisting of lower case Latin letters). It's guaranteed that no two subjects are the same.
The (
m
+ 2)-th line contains
m
integers
t
i
(1 ≤
t
i
≤ 1000) — time in minutes that Valera spends to solve problems of the
i
-th subject. Then follow four lines, containing time segments for sleep, breakfast, lunch and dinner correspondingly.
Each line is in format H1:M1-H2:M2, where 00 ≤ H1, H2 ≤ 23, 00 ≤ M1, M2 ≤ 59. Time H1:M1 stands for the first minute of some Valera's action, and time H2:M2 stands for the last minute of this action. No two time segments cross. It's guaranteed that Valera goes to bed not before midnight, gets up earlier than he has breakfast, finishes his breakfast before lunch, finishes his lunch before dinner, and finishes his dinner before midnight. All these actions last less than a day, but not less than one minute. Time of the beginning and time of the ending of each action are within one and the same day. But it's possible that Valera has no time for solving problems.
Then follow
n
lines, each containing the description of students. For each student the following is known: his exam subject
s
i
(
s
i
is a non-empty string of at most 32 characters, consisting of lower case Latin letters), index of the exam day
d
i
(1 ≤
d
i
≤
k
), the exam time
time
i
, and sum of money
c
i
(0 ≤
c
i
≤ 10
6
,
c
i
— integer) that he's ready to pay for Valera's help. Exam time
time
i
is in the format HH:MM, where 00 ≤ HH ≤ 23, 00 ≤ MM ≤ 59. Valera will get money, if he finishes to solve the problem strictly before the corresponding student's exam begins.
Output
In the first line output the maximum profit that Valera can get. The second line should contain number
p
— amount of problems that Valera is to solve. In the following
p
lines output the order of solving problems in chronological order in the following format: index of a student, to whom Valera is to help; index of the day, when Valera should start the problem; time, when Valera should start the problem (the first minute of his work); index of the day, when Valera should finish the problem; time, when Valera should finish the problem (the last minute of his work). To understand the output format better, study the sample tests.
Examples
Input:
3 3 4
calculus
algebra
history
58 23 15
00:00-08:15
08:20-08:35
09:30-10:25
19:00-19:45
calculus 1 09:36 100
english 4 21:15 5000
history 1 19:50 50
Output:
150
2
1 1 08:16 1 09:29
3 1 10:26 1 10:40
Input:
2 2 1
matan
codeforces
1 2
00:00-08:00
09:00-09:00
12:00-12:00
18:00-18:00
codeforces 1 08:04 2
matan 1 08:02 1
Output:
3
2
2 1 08:01 1 08:01
1 1 08:02 1 08:03
Input:
2 2 1
matan
codeforces
2 2
00:00-08:00
09:00-09:00
12:00-12:00
18:00-18:00
codeforces 1 08:04 2
matan 1 08:03 1
Output:
2
1
1 1 08:01 1 08:02 | 33,237 |
Dancing Cows (DCOWS)
It's the spring dance and, in a rare occurrence, the N (1 ≤ N ≤
5000) bulls have been invited to dance with the M (N < M ≤ 5000)
cows (as long as they stay on their very best behavior).
Farmer John, almost obsessive-compulsive in his organization of
dances, wants the spectacle to be as visually attractive as possible.
Thus, he wants to pair up the N bulls with cow partners such that
the total of all the magnitudes of differences in height is minimized.
Bulls have heights B_i (1 ≤ B_i ≤ 1,000,000) and cows have height
C_i (1 ≤ C_i ≤ 1,000,000). Of course, some cows will be unmatched
since N-M of them will have no partners; ignore their heights.
Input
Line 1: Two space-separated integers: N and M.
Lines 2..N+1: Line i+1 contains a single integer: B_i.
Lines N+2..M+N+1: Line i+N+1 contains a single integer: C_i.
Output
Line 1: A single integer that is the minimum of the sum of the absolute value of the height differences that can be achieved.
Sample
Input:
5 7
10
16
12
10
13
7
17
12
10
9
6
11
Input:
4
Explanation
There are five bulls + seven cows with various heights:
Bulls: 10 10 12 13 16
Cows: 6 7 9 10 11 12 17
Here is one way to achieve a total difference of 4:
Bulls: 10 10 12 13 16
Cows: 9 10 11 12 17, with 6 7 unmatched. | 33,238 |
Submerging Islands (SUBMERGE)
Vice City is built over a group of islands, with bridges connecting them. As anyone in Vice City knows, the biggest fear of vice-citiers is that some day the islands will submerge. The big problem with this is that once the islands submerge, some of the other islands could get disconnected. You have been hired by the mayor of Vice city to tell him how many islands, when submerged, will disconnect parts of Vice City. You should know that initially all the islands of the city are connected.
Input
The input will consist of a series of test cases. Each test case will start with the number N (1 ≤ N ≤ 10^4) of islands, and the number M of bridges (1 ≤ M ≤ 10^5). Following there will be M lines each describing a bridge. Each of these M lines will contain two integers Ui, Vi (1 ≤ Ui,Vi ≤ N), indicating that there is a bridge connecting islands Ui and Vi. The input ends with a case where N = M = 0.
Output
For each case on the input you must print a line indicating the number of islands that, when submerged, will disconnect parts of the city.
Example
Input:
3 3
1 2
2 3
1 3
6 8
1 3
6 1
6 3
4 1
6 4
5 2
3 2
3 5
0 0
Output:
0
1 | 33,239 |
Chinese game (CHIGAME)
Little Mark went to China and learned an ancient Chinese game dating from the 3
rd
century. In this game every player chooses two numbers A, B (all pairs of numbers B must be coprime). The players gather around in a circle. Initially each player puts A beans in front of the player on his left. At this point each player writes down on their notebook the number of beans he has in front of him. Now the game starts by rounds. On every round each player will place B beans in front of the player at his right. Then each player writes down on their notebook the number of beans in front of them. The rounds keep going until there is a number C that all players have written on their notebook. The winner is the player with more numbers written before C.
For example, lets suppose there are three players, Mark, George and Mike. They choose the numbers 15 5, 17 8 and 16 7 respectively. Initially Mark would put 15 beans in front of Mike, George would put 11 beans in front of Mark and Mike would but 16 beans in front of George. Then everybody writes down the number in front of them (17, 16 and 15). Now on each round Mark will put 5 beans in front of George, George will put 8 beans in front of Mike, and Mike will put 7 beans in front of Mark. The following table summarizes the numbers written on each person’s notebook:
Mark George Mike
17 16 15
24 21 23
31 26 31
38 31 39
The last row of the table is the last round of the game, since the number 31 has already been written down by each player. So now the winner is George, since he has 3 numbers written before the 31.
Your task is to print the amount of numbers that the winner wrote before the common number C showed up. Since the game can get quite boring, in all the games the winner will have less than 2
31
numbers written on his notebook.
Input
The input will begin with the number N of players (2 ≤ N ≤ 10). Following, there will be N lines, each containing a pair of numbers Ai, Bi (0 ≤ A ≤ 10
6
, 2 ≤ B ≤ 100) indicating the numbers A and B for player i.
The end of the input will be a case with N = 0.
Output
For each test case on the input you must print a line containing the amount of lines that the winner wrote before the common number C.
Example
Input:
3
15 5
17 8
16 7
2
1 2
1 3
0
Output:
3
0 | 33,240 |
Maximum Girth (MAXGRITH)
In
graph theory
, the
girth
of a graph is the length of a shortest
cycle
contained in the graph. Can you find the maximum girth a graph with
N
-vertices and (
N+1
) edges could possibly have?
Since the answer could be large output the answer modulo 10^9+7.
Input
The first line contains single integer
T
- the number of test cases. Each of the next
T
lines contains a single integer
N
.
Output
For every test case output the maximum girth (modulo 10^9+7) in a separate line.
Example
Input:
3
45
3434
5656565
Output:
30
2290
3771044
Constraints
1 <= T <= 1000
1 <= N <= 10^18 | 33,241 |
The Foxens Treasure (UOFTAB)
Marlin engaged Dory, last April and they decided to marry in next November. Unfortunately, Dory is not like normal girls who their dowry is money, rings or furniture! She has many pictures of fishes and she wants a program that draws boxes around the fishes in the images. Time is passing and Marlin’s program just process the image and output some data that could be used to find the correct locations of these boxes. Please help him to save his marriage dream.
Marlin outputs for every image:
2 integers H and K.
A 2D matrix M of integer values from 1 to K.
T integer vectors V
i
, each of length K. Each vector is coupled with an integer value X
i
.
A Score Evaluator function is used to calculate the score of any box in the image, such that the higher box score, the more confidence in the box to tightly contain a fish. Hence, Marlin targets the box with the highest score that contains a fish.
Given 4 corners of box B, the function works as following:
Construct vector V that has the frequencies of the values in M corresponding to B.
Calculate the score as: Score = H + $\sum_{1}^{T}[X_i * (V.V_i)]$, where (a.b) means the dot product.
Input
The first line of input contains an integer S that represents the number of test cases, then S test cases follow. Each test case start with a line of 5 numbers R C H K T, where R and C are number of rows and columns for the matrix. K, T and H are as described in the problem. R lines follow each with C numbers corresponding to the matrix. Then T lines for the vectors follow each line starts with X of that vector, then K numbers of the vector.
1 ≤ R, C, H ≤ 100, 1 ≤ K ≤ 500, 0 ≤ T ≤ 500, 0 ≤ G ≤ 100 and -5 ≤ X ≤ 5. G is the range of values for vectors V
i
.
Output
For each test case, output on a single line “Case #K:” where K is the number of the test case, followed by a single integer which is the score of the box with highest to have a fish.
Example
Input:
1
3 4 7 3 2
1 1 2 2
1 2 2 3
2 3 1 3
-3 1 1 2
4 7 2 10
Output:
Case #1:
234
Explanation:
Let's evaluate the first 2x2 box which is:
1 1
1 2
1 occurred 3 times, 2 occurred 1 time and 3 occurred 0 times.
Then the frequencies vector is [3 1 0] and its function evaluation is:
7 + (- 3 * ([3 1 0]. [1 1 2]) + 4 * ([3 1 0].[7 2 10]) ) = 7 + (-12 + 92) = 87 | 33,242 |
Foxhole (UOFTAC)
Everyone knows that Foxen love digging holes. You've been observing one Fox in particular, who's preparing to burrow underground in search of treasures. When viewed from the side, as a cross-section, his digging site can be represented as a grid of cells, $H$ ($1 \leq H \leq 100$) deep and $W$ ($1 \leq W \leq 100$) across. Every cell contains either dirt (represented by "D"), stone ("S"), empty space ("E"), or a treasure ("T"). The surface can also be traversed, effectively giving the grid an additional row of empty cells above the topmost row.
The Fox starts immediately above the top-left cell, which is guaranteed to not be empty. It has a set of $N$ ($1 \leq N \leq 1000$) actions in mind before it starts its dig, which it will execute in order. Each action consists of moving either left (represented by "L"), right ("R"), or down ("D") by one cell. If the cell that the Fox would move to contains stone, or is beyond the boundaries of the grid in any direction, it will skip that action. If it enters a cell with a previously-uncollected treasure, it will collect it, leaving the cell empty. If the cell immediately below the Fox is ever empty, it will fall down until this is no longer the case. Note that collecting treasure occurs before falling, and that the Fox stops falling if it hits the bottom of the grid.
There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each one, you'd like to determine how many treasures the Fox will collect throughout the course of its dig.
Input
First line: 1 integer, $T$
For each scenario:
First line: 3 integers, $H$, $W$, and $N$
Next $H$ lines: $W$ characters, representing the $i$th row of the grid, for $i = 1..H$
Next $N$ lines: 1 character, representing the $i$th action, for $i = 1..N$
Output
For each scenario:
1 integer, the number of treasures collected in total.
Example
Input:
2
2 3 4
DDD
TES
R
D
R
L
3 2 6
TE
TE
ET
R
R
L
R
L
R
Output:
1
2
Explanation of Sample:
In the first scenario, the Fox moves right along the surface, then digs down to the first row. As the cell below it is empty, it immediately falls to the 2nd row. It ignores its next action, as the cell to its right is filled with stone, and finally moves left to claim a treasure.
In the second scenario, it moves to the right and promptly falls all the way down to the 2nd row. Because the Fox is already in the rightmost column, it ignores the action to move right. It then moves left, collects the treasure there, and then falls to the bottom row. Finally, it moves back and forth between the bottom-left and bottom-right cells twice - however, it only collects the treasure in the latter cell the first time. | 33,243 |
Reverse Fox Hunt (UOFTAD)
A family of Foxen, having caught a pesky farmer on their property, want to teach him a lesson. Of course, they're not cruel - they plan to simply prevent him from returning home to his farm, until he's willing to beg them for mercy.
The Foxen and the farmer live in a forest, which may be viewed as a grid of cells, with $H$ ($1 \leq H \leq 6$) rows of $W$ ($1 \leq W \leq 6$) cells each. Each cell contains either grass (represented by "G"), trees ("T"), the farmer ("F"), or his farm ("H"). The farmer may repeatedly move up, down, left, or right to adjacent cells within the grid, provided that they are not blocked by trees. Due to his overconfidence in exploring the forest, the farmer is not directly adjacent to his farm.
The family of Foxen can also block the farmer's way, by standing in grass-filled cells. He would not, of course, dare to enter a cell with a Fox in it. However, the Foxen do have better things to do, so they'd like to determine the minimum number of cells they must occupy in order to prevent the farmer from ever reaching his farm.
There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each one, you'd like to answer the Foxen's question. Note that no Foxen might be necessary, if the trees already bar the farmer's way sufficiently.
Input
First line: 1 integer, $T$
For each scenario:
First line: 2 integers, $H$ and $W$
Next $H$ lines: $W$ characters, representing the $i$th row of the grid, for $i = 1..H$
Output
For each scenario:
1 integer, the minimum number of Foxen necessary to block the farmer.
Example
Input:
2
1 5
FGTGH
4 5
GGGGG
GFGTG
GTTGH
GGGGG
Output:
0
2
Explanation of Sample
In the first scenario, the farmer can already never reach his farm, so no Foxen are necessary.
In the second scenario, one possible placement of two Foxen (each represented by an "X") is as follows:
GGGGX
GFGTG
GTTGH
GGXGG | 33,244 |
Foxling Feeding Frenzy (UOFTAE)
You've come across $N$ ($1 \leq N \leq 200$) adorable little Foxlings, and they're hungry! Luckily, you happen to have $M$ ($1 \leq M \leq 200$) crackers on hand, and everyone knows that Foxen love crackers! You'd like to distribute all of your crackers, without splitting any of them, among the Foxlings - but you have to be careful. Foxling $i$ must be fed at least $A_i$ crackers, or it will remain hungry, but no more than $B_i$ of them, or it will become hyper ($1 \leq A_i \leq B_i \leq 200$). You certainly don't want any hungry or hyper Foxlings on your hands, and you're curious as to how many ways this can be accomplished.
There are $T$ ($1 \leq T \leq 100$) scenarios as described above. For each one, you'd like to determine the number of different distributions of your crackers that would satisfy all of the Foxlings, modulo $10^9+7$ (as this value can be quite large).
Input
First line: 1 integer, $T$
For each scenario:
First line: 2 integers, $N$ and $M$
Next $N$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..N$
Output
For each scenario:
Line 1: 1 integer, the number of valid cracker distributions modulo $10^9+7$
Example
Input:
2
2 5
1 4
2 6
3 5
2 2
2 9
2 3
Output:
3
0
Explanation of Sample
In the first scenario, you can give either 1, 2, or 3 crackers to the first Foxling, and the remaining 4, 3, or 2 (respectively) to the second.
In the second scenario, each Foxling must receive at least 2 crackers, while you only have 5 to give out, so you have no valid options. | 33,245 |
Foxic Expressions (UOFTAF)
Let's talk about some definitions, shall we?
An uppercase letter is a character between "A'' and "Z'', inclusive. You knew that.
A string is a sequence of characters. You probably knew that.
A Foxic letter is a superior uppercase letter - namely, one of "F", "O", or "X". You probably didn't know that.
A Foxic string is a superior string, consisting only of Foxic letters. You didn't know that.
Finally, a Foxic expression is a special string, with each of its characters being either a Foxic letter, or an "n" immediately following a Foxic letter. A Foxic expression can be translated into a Foxic string by a three-step process. First, up to one character can be added, removed, or modified, provided that the resulting string is still a valid Foxic expression. Next, every Foxic letter immediately preceding an "n" is replaced by zero or more occurrences of that same letter. Finally, each "n" is removed. You most certainly did not know that.
There are $T$ ($1 \leq T \leq 100$) scenarios to consider, as described above. In each scenario, given a Foxic string $S$ of length $N$ ($1 \leq N \leq 100$) and a Foxic expression $E$ of length $M$ ($1 \leq M \leq 100$), you'd like to determine whether or not $E$ can be translated into $S$.
Input
Line 1: 1 integer, $T$
For each scenario:
Line 1: 1 integer, $N$
Line 2: 1 string, $S$
Line 3: 1 integer, $M$
Line 4: 1 string, $E$
Output
For each scenario:
The string "Yes" (without quotes) if $E$ can be translated into $S$, or "No" otherwise.
Example
Input:
2
5
OOOFO
7
OXnFOXn
3
FOX
7
OFnOXnO
Output:
Yes
No
Explanation of Sample:
In the first scenario, one possible course of action is to erase the second character of $E$, leaving the Foxic expression "OnFOXn". Next, we may choose to replace the first "O" with three copies of "O", and the remaining "X" with zero occurrences of "X", since each of these precedes an "n" - this yields the string "OOOnFOn". Finally, after removing each "n", we are left with "OOOFO", which matches $S$. Replacing the second character with an "O" would have also been possible.
In the second scenario, it is impossible to translate $E$ into $S$ through any valid steps. | 33,246 |
Attack of the Bloons (UOFTBB)
The Bloons (not to be confused with balloons) are attacking! They are attempting to navigate your course of $L$ ($1 \leq L \leq 1000$) cells, laid out in a row and numbered from $1$ to $L$. You don't know what they'll do to you if they manage reach the end, and you don't want to find out! To that end, you've constructed some defensive towers along the course. You might say that this is a Bloons Tower Defense.
There are $N$ ($1 \leq N \leq 1000$) towers ready to take out any Bloons that get close. The $i$th tower is located next to cell $C_i$ ($1 \leq C_i \leq L$), and can launch darts at any Bloons that are no more than $R_i$ ($0 \leq R_i \leq 1000$) cells away - that is, Bloons in cells $C_i-R_i$ to $C_i+R_i$, inclusive. Every second, it will do $D_i$ ($1 \leq D_i \leq 10^9$) HP worth of damage to any Bloons in this range.
$M$ ($1 \leq M \leq 1000$) Bloons will attempt to float through your course, one after another. The $i$th Bloon begins with $H_i$ ($1 \leq H_i \leq 10^9$) HP, and will pop as soon as it has taken at least that much damage in total. Each Bloon starts in cell 1, and moves along the course at a speed of 1 cell per second. If a Bloon moves past cell $L$, it safely exits the course and can no longer be popped.
There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each, you'd like to determine how far along the course each of the $M$ Bloons will make it.
Input
First line: 1 integer, $T$
For each scenario:
First line: 2 integers, $L$ and $N$
Next $N$ lines: 3 integers, $C_i$, $R_i$, and $D_i$, for $i = 1..N$
Next line: 1 integer, $M$
Next $M$ lines: 1 integer, $H_i$, for $i = 1..M$
Output
For each scenario:
$M$ lines: If the $i$th Bloon will survive the course, the string "Bloon leakage" (without quotes) - otherwise, 1 integer, the furthest cell which the $i$th Bloon will reach, for $i = 1..M$
Example
Input:
1
10 3
3 3 1
4 0 4
10 2 2
4
1
20
9
11
Output:
1
Bloon leakage
5
8
Explanation of Sample:
The following diagram illustrates which cells each tower can hit:
The first Bloon, having only 1 HP, will go down to the first tower in cell 1.
The second Bloon will manage to clear the course, surviving past cell 10 with 4 HP remaining.
The third Bloon will lose its final HP while at cell 5, having taken 5 damage from the first tower, and 4 from the second.
The final Bloon will survive past cell 6 with 1 HP remaining, but will then go down at cell 8 when it takes 2 damage from the third tower. | 33,247 |
Homemade Asteroids (UOFTBC)
Pew pew pew!
Everyone loves Asteroids, the classic arcade game involving senselessly blasting asteroids into submission with a spaceship. In fact, you love it so much that you built your very own version to play at home! Unfortunately, it sucks.
Your version of the game is played on a 2D plane, containing your ship (a dot at coordinates ($X_S$, $Y_S$)) and $N$ ($1 \leq N \leq 1000$) stationary, triangular, positive-area asteroids. The $i$th asteroid has vertices at coordinates ($X_{Ai}$, $Y_{Ai}$), ($X_{Bi}$, $Y_{Bi}$), and ($X_{Ci}$, $Y_{Ci}$). All coordinates in the input are integers with absolute values no greater than $10^9$, and no two objects occupy any of the same space (even on their edges or vertices).
Your game only permits you to fire a single missile, which travels in a straight line, destroying every asteroid that it comes in contact with (even on its edges or vertices). However, it doesn't exactly move very smoothly - instead, it starts at your ship at frame 0, and after every frame, its x-coordinate increases by $X_D$, and its y-coordinate by $Y_D$. These variables also have absolute values no greater than $10^9$, and at least one of them is guaranteed to be non-zero. After frame $F$ ($1 \leq F \leq 1000$), the missile simply disappears.
There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each, you'd like to predict how many different asteroids your missile will be able to take out before frame $F+1$.
Input
First line: 1 integer, $T$
For each scenario:
First line: 2 integers, $N$ and $F$
Second line: 4 integers, $X_S$, $Y_S$, $X_D$, and $Y_D$
Next $N$ lines: 6 integers, $X_{Ai}$, $Y_{Ai}$, $X_{Bi}$, $Y_{Bi}$, $X_{Ci}$, and $Y_{Ci}$, for $i = 1..N$
Output
For each scenario:
1 integer, the number of asteroids that will be destroyed by the missile
Example
Input:
1
4 4
4 17 4 -2
5 16 15 18 12 9
16 13 13 11 14 10
20 9 20 7 18 7
22 5 23 11 27 6
Output:
2
Explanation of Sample
The following grid shows the layout of the game, with your ship marked with an "S", and the missile's location at each frame marked with that frame's number:
As can be seen, the missile destroys the first asteroid during frame 1, and then the third asteroid during frame 4. It does not destroy the second asteroid, even though its line of fire goes through it, as it does not intersect the asteroid during any of the frames. It also doesn't destroy the last asteroid, as it stops travelling after frame 4. | 33,248 |
Diablo Bot (UOFTBD)
Maybe you've played Diablo? There are three different character classes: Noobs, Suckers, and Pros. Noobs don't know anything about the game. Suckers think they know how to play. Pros know that the goal of the game is to write a script that will farm for valuable items that they can turn around and sell to Suckers on the black market. Obviously Pros would sell to Noobs if they could, but Noobs don't even know how to buy items.
An obvious piece of prerequisite information for making such a bot is knowing what sorts of items are worth picking up. There are Normal, Magic, Rare, and Set items:
Set items always belong to some famous dead person, so they always begin with a word that ends in "
's
" (e.g.
Andrew's
). No other items are special enough to begin this way.
Rare items always have names that are two words long.
Magic items always have names that are between two and four words long, inclusive. If, and only if, a Magic item has more than two words in its name, then the last two words are "
of [something]
" (e.g.
of Doom
).
If the first word is "
Damaged
", the item is a Normal item. Furthermore, any item that could not possibly be Magic, Rare, or Set must also be Normal. No other items are Normal.
You may not have played Diablo, but hopefully you still know that a "word" is a maximal substring of non-space characters. Also, letter case is irrelevant.
You have a list of $N$ ($1 \leq N \leq 1000$) item names, and you need to be able to classify these items as accurately as possible. It may not be possible to assign a unique type to each item, but as long as it's not Normal, surely you'll want it. Every item name is a string of no more than 100 characters, containing only alphabetic characters, spaces, and apostrophes. Every name begins and ends with a non-space character.
Input
First line: 1 integer, $N$
Next $N$ lines: The name of the $i$th item, for $i = 1..N$
Output
$N$ lines: The type of the $i$th item (one of "Normal", "Set", "Magic", or "Rare"), or "Not sure, take anyways" (without quotes) if the item's type cannot be determined, but is known not to be Normal, for $i = 1..N$
Example
Input:
7
Somebody's Something of Whatever
stone of jordan
Wirt's Leg
FLAMING TURNIP
Damaged Goods
Sword
Fish shaped volatile organic compounds
Output:
Set
Magic
Set
Not sure, take anyways
Normal
Normal
Normal
Explanation of Sample:
The first and third items begin with possessives, so they must be Set items. The second item is three words long, and ends in "of [something]" so it must be Magic. The fourth item could be either Rare or Magic. The fifth item begins with "Damaged" so it's Normal. The last two items don't fit the descriptions of Set, Rare, or Magic, so they must be Normal also. | 33,249 |
MVP (UOFTBE)
It's down to the final match in the world's biggest SC2$^1$ tournament! You're the MVP$^2$ of MVP$^3$, and you're going up against MVP$^4$. There are $G$ ($1 \leq G \leq 20$) games in the series, with a winner decided after all have been played. Being a Protoss$^5$ player, you know the perfect way to win against that Terran$^6$ scum - with a cannon rush$^7$ every single game. Now you just have to execute it perfectly, by quickly getting your probe$^{10}$ to the correct location, and the prize money's sure to be yours.
Each game will take place on a map which can be represented as a grid with $H$ ($2 \leq H \leq 1000$) rows of $W$ ($2 \leq W \leq 1000$) cells each. Each cell contains either empty space (represented by "E"), water ("W"), a unit ("U"), one of exactly two mineral patches ("M"), the probe ("P"), or the cannon rush site ("C"). Every second, your probe can move to a horizontally- or vertically-adjacent cell within the grid, with the goal of reaching the cannon rush site in as little time as possible. It can move freely from an empty cell to another empty cell (including its initial position and destination), while cells containing water or minerals may never be traversed.
Normally, the probe may also not pass through units. However, it
can
if it is travelling towards a mineral patch. Specifically, the probe can only leave or enter a cell containing a unit if, for at least one of the two mineral patches on the map, the cell which the probe is entering is closer to that patch than the cell which the probe is leaving. Closeness is defined according to the minimum amount of time it would take to reach the mineral patch from the given cell, assuming the ability to pass through all units on the way.
For each game, you'd like to determine whether or not you can be successful in your strategy, and, if so, how quickly you can execute the cannon rush. Of course, the point of this is to help prepare the correct BM$^{11}$ for the end of the game.
Input
First line: 1 integer, $G$
For each game:
First line: 2 integers, $H$ and $W$
Next $H$ lines: $W$ characters, representing the $i$th row of the map, for $i = 1..H$
Output
For each game:
The BM to be typed at the conclusion of the game. Namely, if the probe can reach the cannon rush site, the string "pwned you in $X$ seconds eZ$^{12}$, learn to play n00b$^{13}$" (without the quotes and glossary numbers), where $X$ is the minimum number of seconds for it to do so - otherwise, the string "terran so broken, apologize for playing this race".
Example
Input:
2
4 5
WWEMC
EEEUE
PUWWU
MEEEE
5 4
EWEM
ECUE
EEWE
EWEE
EUPM
Output:
pwned you in 8 seconds eZ, learn to play n00b
terran so broken, apologize for playing this race
Explanation of Sample:
In the first scenario, the single shortest path that the probe may take to the cannon rush site is illustrated below:
Note that the first move is made by going "towards" the top-right mineral patch, while the second move is made by going towards the bottom-left one.
In the second scenario, the probe is unable to pass through any of the units, due to the locations of the mineral patches, and as such cannot reach its destination.
Glossary of Terms:
$^1$
SC2:
StarCraft 2, by Blizzard Entertainment - a game of kings
$^2$
MVP:
Most valuable player
$^3$
MVP:
A top Korean SC2 team
$^4$
MVP:
A top Korean Terran player (who is not on the team MVP)
$^5$
Protoss:
The most pleasant race in SC2, which only nice people use
$^6$
Terran:
The most despicable race in SC2, which no decent human being would consider
$^7$
Cannon rush:
The act of building proxy$^8$ cannons, a common type of cheese$^9$
$^8$
Proxy:
A structure made near or in your opponent's base, instead of your own
$^9$
Cheese:
A perfectly legitimate strategy which can allow you to win quickly, while leaving your opponent mad
$^{10}$
Probe:
A Protoss unit most useful for its ability to make cannons
$^{11}$
BM:
Customary parting words for your opponent, used to convey your respect for them
$^{12}$
eZ:
Easy
$^{13}$
n00b:
A player whose skill is somewhat lacking in calibre | 33,250 |
Light Cycling (UOFTBF)
Having been sucked into your father's secret computer through a projector in the back of his arcade (or something), you find yourself in the wonderful world of Tron! Here, you play games all day, and if you ever lose, you die.
One such game involves you and an opponent driving around a flat grid on light cycles, which leave behind a permanent trail of...light...wherever they go. This grid can be modeled with the Cartesian plane, and is enclosed by a rectangle of impenetrable walls which ensure that the x-coordinate of each light cycle is always between $1$ and $10^{12}$, while its y-coordinate is between $1$ and $10^6$ (inclusive). Light cycles always stay on the grid lines, and move at a speed of 1 square per second.
A match lasts $S$ ($1 \leq S \leq 10^{100}$) seconds. You start at coordinates ($X_A$, $Y_A$) and follow a set of $N_A$ ($1 \leq N_A \leq 10^5$) instructions, with your $i$th instruction consisting of moving $L_{Ai}$ squares in the direction given by the character $D_{Ai}$ (with "U", "D", "L", and "R" representing up, down, left, and right, respectively). Similarly, your opponent starts at coordinates ($X_B$, $Y_B$) and follows a set of $N_B$ ($1 \leq N_B \leq 10^5$) instructions, with their $i$th instruction described by $L_{Bi}$ and $D_{Bi}$. Of course, neither player's instructions will ever take them beyond the boundaries of the walls, and it will take each player exactly $S$ seconds to execute their instructions. Additionally, for each player, no instruction will have an equal or opposite direction to that of their previous instruction. Finally, if a grid point is ever visited more than once throughout the course of the match, it is guaranteed that one of the path segments intersecting there is passing directly through vertically, while the other is passing directly through horizontally (as such, this cannot happen at either player's starting or ending points).
Whenever both light cycles reach the same grid point at the same time, or a light cycle hits an existing trail of light (in other words, a grid point which either light cycle had previously passed through), a collision occurs. Because you're just playing a practice match for now, neither player dies when this occurs, and, in fact, the collision is not counted in favour of either you or your opponent. Instead, for $T$ ($1 \leq T \leq 20$) scenarios as described above, you're simply interested in the number of collisions that will occur throughout each match.
Input
First line: 1 integer, $T$
For each scenario:
First line: 1 integer, $S$
Next line: 3 integers, $X_A$, $Y_A$, and $N_A$
Next $N_A$ lines: 1 character, $D_{Ai}$, and 1 integer, $L_{Ai}$, for $i = 1..N_A$
Next line: 3 integers, $X_B$, $Y_B$, and $N_B$
Next $N_B$ lines: 1 character, $D_{Bi}$, and 1 integer, $L_{Bi}$, for $i = 1..N_B$
Output
For each scenario:
1 integer: The total number of collisions that will occur.
Example
Input:
1
12
2 5 5
R 4
U 1
L 1
D 4
L 2
3 3 4
U 3
L 2
D 2
R 5
Output:
4
Explanation of Sample:
The following diagram illustrates the paths of the light cycles (yours drawn in solid lines, and your opponent's drawn in dotted ones), as well as all of the collision points (indicated with large dots): | 33,251 |
Your Rank is Pure (EXTREME ver) (EGCJPURE)
Note: The problem description is same as
GCJPURE
, but with higher constraints (to become more challenging), more strict time limit (to reject bad complexity), and more strict source limit (to reject hardcoded precomputation). Good Luck.
Pontius: You know, I like this number 127, I don't know why.
Woland: Well, that is an object so pure. You know the prime numbers.
Pontius: Surely I do. Those are the objects possessed by our ancient masters hundreds of years ago. Oh, yes, why then? 127 is indeed a prime number as I was told.
Woland: Not... only... that. 127 is the 31st prime number; then, 31 is itself a prime, it is the 11th; and 11 is the 5th; 5 is the 3rd; 3, you know, is the second; and finally 2 is the 1st.
Pontius: Heh, that is indeed... purely prime.
The game can be played on any subset S of positive integers. A number in S is considered pure with respect to S if, starting from it, you can continue taking its rank in S, and get a number that is also in S, until in finite steps you hit the number 1, which is not in S.
When n is given, in how many ways you can pick S, a subset of {2, 3, ..., n}, so that n is pure, with respect to S? The answer might be a big number, you need to output it modulo 10
9
+7.
Input
The first line of the input gives the number of test cases,
T
.
T
lines follow. Each contains a single integer
n
.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the answer as described above.
Constraints
T
<10
5
2≤
n
≤10
5
Note: These constraints were selected carefully.
Example
Input:
2
5
6
Output:
Case #1: 5
Case #2: 8
Other Info
Sorry for slow language users, I've made an experiment and the result is if I set constraints that allow slow languages to be accepted with 'good' complexity O(f(n)), then the 'bad' complexity O(f(n)*log(n)) could be accepted too using fast language (Because slow language is ~80x slower than fast language). I don't want this to happen. But don't feel so bad :-) I've made
this tutorual problem
that allow slow languages to be accepted (except maybe: PIKE).
Time limit ~4× My Program top speed (25.53s using 1744B of C code).
You can see my submission history and time record for this problem
:
here
See also:
Another problem added by Tjandra Satria Gunawan | 33,252 |
Yell Classico (CLASSICO)
The Old Yellers, the contestants of the old days of IIUC are going to have a football match with the current contestants. As the yellers are going to be the host of the match, it will be called 'Yell Classico'. As the yellers are always busy in yelling, oops, I mean programming, they have appointed you as the manager of their team. Now, as a manager of the Yeller team, you have to select 11 players for the match from
N
players.
All the
N
players will stand in a line just before the match. Your task will be to select 11 players from them in such a way that the player standing in front is as tall as possible. If there are more than one such team formations, do it in a way where the 2nd player is as tall as possible. If still there is a tie, choose the formation having tallest player in the 3rd position and so on. (Which means, until you can break the tie or reach the 11th position, keep looking in the next position).
Note that:
You don't have enough time to change the order in which players are standing.
If you have tie even after reaching the 11th position, select from any of the tied formations.
Players are quite same in their playing abilities, you don't need to bother about that.
Input
First line of input will contain the number of test cases,
T
< 100.
For each test case, there are two lines.
The first line contain
N
(number of players, 1 <
N
< 2000).
The second one is a line of
N
integers separated by spaces. The ith integer of this line will specify the height of the ith player. (Heights will not be greater than 10
9
).
Output
For each test case output '
Case
X
:
', (
X
is the case number, starting from 1). Then print the heights of the 11 selected players separated by spaces. If it's not possible to select exactly 11 players, then send the spectators home by printing '
go home!
' (Without quotations). See the sample output for exact formatting.
Example
Input:
4
15
2 10 8 5 1 5 9 9 3 5 6 6 2 2 8
11
2 6 3 8 7 2 5 3 4 3 3
4
2 7 9 6
12
6 2 3 8 7 2 5 3 4 3 3 10
Output:
Case 1: 10 8 9 9 3 5 6 6 2 2 8
Case 2: 2 6 3 8 7 2 5 3 4 3 3
Case 3: go home!
Case 4: 6 3 8 7 2 5 3 4 3 3 10
Problem Setter: Bidhan Roy | 33,253 |
Elegant Diamond (GCJ102A)
Problem
The king has hired you to make him an elegant diamond. An elegant diamond is a two-dimensional object made out of digits that's symmetric about a horizontal and a vertical axis. For example, the following four shapes are elegant diamonds:
2 8 3 7
3 3 8 8 2 2
4 1 4 8 3
3 3
2
These three shapes are diamonds, but are not elegant:
2 1 3
1 1 1 2 1 1
1 1 1 1 3 1 3
2 1 1 1
1 2
These three shapes are not diamonds:
1 2 8 8
1 1 222 0
2 00000
The king will start by giving you a diamond, which may not be elegant. Your job is to make it elegant by
enhancing
it, adding digits on to make a bigger diamond. Because you don't want to spend too much money, you want to do it with as little
cost
as possible.
Definitions
A
diamond of size
k
is 2k-1 lines of digits, 0-9, separated by single spaces, organized in the following way:
Line i (1 ≤ i ≤ k) contains k-i spaces, then i digits separated by single spaces.
Line i (k < i < 2k) contains i-k spaces, then 2k-i digits separated by single spaces.
An
elegant diamond of size
k
is a diamond of size k with the following two symmetry properties:
Horizontal symmetry: Let c
i
be the number of digits on line i. The j
th
digit on line i (where j=1 for the first digit) must be the same as the c
i
+1-j
th
digit.
Vertical symmetry: The j
th
digit on line i (where i=1 for the first line) must be the same as the j
th
digit on line 2k-i.
A diamond of size k can be
enhanced
by adding digits to it. The result of enhancing a diamond of size k has the following properties:
The result is a diamond of size ≥ k.
The original diamond is part of the result. In other words, there exist some X and some Y such that, for all values of i and j such that the j
th
character of the i
th
line of the original is a digit (as opposed to a space), the j+X
th
character on the i+Y
th
line of the result is also a digit and it's the same as the j
th
character on the i
th
line of the original.
The
cost
of enhancing a diamond is equal to the number of digits in the result of the enhancement, minus the number of digits in the original diamond.
Input
The first line of the input gives the number of test cases,
T
.
T
test cases follow. Each test case consists of a single integer
k
in a line on its own, followed by a diamond of size
k
.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the minimum cost required to enhance the given diamond into an elegant diamond. If the diamond is already elegant, y=0.
Limits
1 ≤
T
≤ 100.
1 ≤
k
≤ 51.
Sample
Input
4
1
0
2
1
2 2
1
2
1
1 2
1
3
1
6 3
9 5 5
6 3
1
Output
Case #1: 0
Case #2: 0
Case #3: 5
Case #4: 7
Explanation
There are four cases. The first two cases start as elegant diamonds of size 1 and 2, respectively, and don't need to be enhanced; so the cost is 0. The third case can be enhanced to look like:
3
1 1
1 2 1
1 1
3
There are several possible enhancements, but this is one with the lowest possible cost, which is 5. n the fourth case we can enhance the diamond into the following elegant diamond for a cost of 7:
9
1 1
6 3 6
9 5 5 9
6 3 6
1 1
9 | 33,254 |
World Cup 2010 (GCJ102B)
After four years, it is the World Cup time again and Varva is on his way to South Africa, just in time to catch the second stage of the tournament.
In the second stage (also called the knockout stage), each match always has a winner; the winning team proceeds to the next round while the losing team is eliminated from the tournament. There are 2
P
teams competing in this stage, identified with integers from 0 to 2
P
- 1. The knockout stage consists of P rounds. In each round, each remaining team plays exactly one match. The exact pairs and the order of matches are determined by successively choosing two remaining teams with lowest identifiers and pairing them in a match. After all matches in one round are finished, the next round starts.
In order to help him decide which matches to see, Varva has compiled a list of constraints based on how much he likes a particular team. Specifically, for each team
i
he is
willing to miss at most
M[i]
matches the team plays in the tournament.
Varva needs to buy a set of tickets that will guarantee that his preferences are satisfied, regardless of how the matches turn out. Other than that, he just wants to spend as little money as possible. Your goal is to find the
minimal amount of money
he needs to spend on the tickets.
Tickets for the matches need to be purchased in advance (before the tournament starts) and the ticket price for each match is known. Note that, in the small input, ticket prices for all matches will be equal, while in the large input, they may be different.
Example
A sample tournament schedule along with the ticket prices is given in the figure above. Suppose that the constraints are given by the array
M = {1, 2, 3, 2, 1, 0, 1, 3}
, the optimal strategy is as follows: Since we can't miss any games of team 5, we'll need to spend 50, 400, and 800 to buy tickets to all the matches team 5 may play in. Now, the constrains for the other teams are also satisfied by these tickets, except for team 0. The best option to fix this is to buy the ticket for team 0's first round match, spending another 100, bringing the total to 1350.
Input
The first line of the input gives the number of test cases,
T
.
T
test cases follow. Each case starts with a line containing a single integer
P
. The next line contains 2
P
integers -- the constraints
M[0]
, ...,
M[2
P
-1]
.
The following block of
P
lines contains the ticket prices for all matches: the first line of the block contains 2
P-1
integers -- ticket prices for first round matches, the second line of the block contains 2
P-2
integers -- ticket prices for second round matches, etc. The last of the
P
lines contains a single integer -- ticket price for the final match of the World Cup. The prices are listed in the order the matches are played.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the minimal amount of money Varva needs to spend on tickets as described above.
Limits
1 ≤
T
≤ 50
1 ≤
P
≤ 10
Each element of
M
is an integer between 0 and
P
, inclusive.
All the prices are integers between 0 and 100000, inclusive.
Sample
Input
2
2
1 1 0 1
1 1
1
3
1 2 3 2 1 0 1 3
100 150 50 90
500 400
800
Output
Case #1: 2
Case #2: 1350 | 33,255 |
Bacteria (GCJ102C)
A number of bacteria lie on an infinite grid of cells, each bacterium in its own cell.
Each second, the following transformations occur (all simultaneously):
If a bacterium has no neighbor to its north and no neighbor to its west, then it will die.
If a cell has no bacterium in it, but there are bacteria in the neighboring cells to the north and to the west, then a new bacterium will be born in that cell.
Upon examining the grid, you note that there are a positive, finite number of bacteria in one or more rectangular regions of cells.
Determine how many seconds will pass before all the bacteria die.
Here is an example of a grid that starts with 6 cells containing bacteria, and takes 6 seconds for all the bacteria to die. '1's represent cells with bacteria, and '0's represent cells without bacteria.
000010
011100
010000
010000
000000
000000
001110
011000
010000
000000
000000
000110
001100
011000
000000
000000
000010
000110
001100
000000
000000
000000
000010
000110
000000
000000
000000
000000
000010
000000
000000
000000
000000
000000
000000
Input
The input consists of:
One line containing
C
, the number of test cases.
Then for each test case:
One line containing
R
, the number of rectangles of cells that initially contain bacteria.
R
lines containing four space-separated integers
X
1
Y
1
X
2
Y
2
. This indicates that all the cells with X coordinate between X
1
and X
2
, inclusive, and Y coordinate between Y
1
and Y
2
, inclusive, contain bacteria.
The rectangles may overlap.
North is in the direction of decreasing Y coordinate, and west is in the direction of decreasing X coordinate.
Output
For each test case, output one line containing "Case #N: T", where N is the case number (starting from 1), and T is the number of seconds until the bacteria all die.
Limits
1 ≤
C
≤ 100.
1 ≤
R
≤ 1000
1 ≤
X
1
≤
X
2
≤ 1000000
1 ≤
Y
1
≤
Y
2
≤ 1000000
The number of cells initially containing bacteria will be at most 1000000.
Sample
Input
1
3
5 1 5 1
2 2 4 2
2 3 2 4
Output
Case #1: 6 | 33,256 |
Team Slide Treasure Hunt Race (SLIDE)
Alice and Bob are participating in an exciting new Olympic event, the Team Slide Treasure Hunt Race! This event takes place on a slide with various treasures on it, which is up to 10m wide and 10km long. Yes, that's kilometers.
The slide can be represented as a grid of cells, with $N$ ($2 \leq N \leq 10^4$) rows and $M$ ($2 \leq M \leq 10$) columns. The rows are numbered $1, 2 \ldots N$ from top to bottom, and the columns are numbered $1, 2 \ldots M$ from left to right. The cell in row $i$ and column $j$ is referred to as cell ($i$, $j$), and contains a treasure with value $G_{i,j}$ ($1 \le G_{i,j} \le 10^5$).
The two friends will each get to travel once down the slide, one after another. First, Alice will slide from the top-left corner of the slide (cell ($1$, $1$)) down to the bottom-left corner (cell ($N$, $1$)). Then, Bob will slide from the top-right corner (cell ($1$, $M$)) down to the bottom-right corner (cell ($N$, $M$)). Whenever a person moves in the slide, they move from their current row to the next row down, and they can also guide themselves left or right by one column if desired. This means that they can go from cell ($i$, $j$) to either cell ($i+1$, $j-1$), ($i+1$, $j$), or ($i+1$, $j+1$), as long as they don't exit the slide. Throughout the race, both Alice and Bob collect the treasure in each cell they slide through - this includes their respective starting and ending cells. However, if Bob goes through any cell that Alice has already visited, he can't collect the treasure in it again.
Alice and Bob would like to determine a sliding plan to allow them to collect as much treasure as possible, and win the gold medal! They've asked you to determine the maximum total value of treasure that they can collect, out of all valid strategies.
Input
The first line of the input will contain two integers $N$ and $M$, separated by a space. Each of the next $N$ lines, for $i$ from $1$ to $N$, will contain the $M$ space-separated integers $G_{i,1} \,\,\, G_{i,2} \,\,\, \dots \,\,\, G_{i, M}$.
Output
Output one number on a line by itself: the maximum combined treasure value that Alice and Bob can collect.
Example
Input:
5 4
3 6 8 2
5 2 4 3
1 1 20 10
1 1 20 10
1 1 20 10
Output:
73
Explanation of Sample
The single optimal sliding plan involves Alice sliding down-right, down-right, down-left, and down-left, followed by Bob sliding down-left, down-right, down-left, and down-right. The treasures collected are shown in bold on the following grid:
Alice collects a total treasure value of $3+2+20+1+1=27$, while Bob collects $2+4+10+20+10=46$. Their total is then $27+46=73$. | 33,257 |
Tourney (TOURNEY)
Don Cherry has been hired to run 24-hour coverage of a series of single-elimination, bracket-style, furniture disassembly tourneys (tournaments). Each competitor has a furniture disassembly skill level, an integer between $1$ and $10^9$. In every head-to-head match, the competitor with the larger skill level wins and moves on, while the other is eliminated from the tourney. It is guaranteed that, at any time, the skill levels of all competitors are distinct, so there are no ties.
There are $2^N$ ($1 \leq N \leq 20$) competitor positions in the tourney tree, numbered $1, 2, \ldots, 2^N$ from left to right. In the first round, competitors 1 and 2 face off in a furniture disassembly race, as do competitors 3 and 4, etc. In each subsequent round, the winners of the first two matches from the previous round compete, as do the winners of the following two, etc. After $N$ rounds, a single winner remains. For example, when $N=2$, the tourney tree looks like this:
where A represents the winner of the match between competitors 1 and 2, B represents the winner of the match between competitors 3 and 4, and C represents the winner of the match between A and B. The winner of this tourney is C.
Because of sponsorship contracts, some competitors will be replaced over time. After any new person comes in, a new tourney is held.
In order to help Don Cherry, you must write a program to compute certain tourney statistics at various points in time, given a sequence of $M$ ($1 \leq M \leq 10^6$) commands - see the input format below.
Input
The first line of input contains two integers, $N$ and $M$.
The next $2^N$ lines, for $i$ from $1$ to $2^N$, each contain one integer $S_i$, indicating the skill level of the initial competitor at position $i$ in the tourney tree.
Each of the following $M$ lines will be a command in one of three formats:
"
R
$i$ $s$" means that the competitor at position $i$ is removed, and replaced with a new one with skill level $s$. A new tourney should then be held.
"
W
" means that your program should determine who won the current tourney. Print out the position $i$ (between $1$ and $2^N$) of this competitor.
"
S
$i$" means that your program should print out the number of rounds that the competitor at position $i$ won in the current tourney.
Output
For each "
W
" or "
S
$i$" command in the input, print out the corresponding integer on a line by itself.
Example
Input:
2 8
30
20
10
40
S 1
W
R 4 9
S 4
W
R 2 35
S 2
W
Output:
1
4
0
1
2
2
Explanation of Sample:
The results of the initial tourney are as follows:
As can be seen, competitor 1 wins 1 match, and competitor 4 wins the entire tourney. After this, competitor 4 is replaced by a new competitor with skill level 9. As can be seen below, this causes a different outcome for the tourney held after the third command:
Finally, the state of the tourney tree after the next competitor replacement (caused by the sixth command) is: | 33,258 |
A Romantic Dinner Outing (RDINNER)
Brian the Computer Science Nerd is going on a date with his girlfriend, Anatevka! His romantic location of choice is a Chinese restaurant.
At this restaurant, $N$ ($1 \leq N \leq 15$) different dishes are available, and Brian would like to order each one exactly once. The waiter will come to his table to take orders $N$ times - the $i$th time he comes will be $W_i$ ($1 \leq W_1 < W_2 < \dots < W_N \leq 10^9$) minutes after the start of the meal. He has quite a poor memory, so each time he comes by, Brian will have a chance to order exactly one new dish.
Dish $i$ takes $T_i$ ($1 \leq T_i \leq 10^9$) minutes to prepare, which means that it will generally come exactly that many minutes after being ordered, delivered by a different waiter who will not take orders. However, meals are guaranteed to arrive in the same order in which they were ordered - this means that, if meal $i$ was ordered before meal $j$, but meal $j$ is ready before meal $i$, then meal $j$ will instead arrive at the same time as meal $i$.
Now, Brian considers time spent waiting for the first meal after the start of the dinner, as well as for each subsequent meal after the previous one, to be idle time. Of course, these are the worst parts of the date, as they require actually engaging in conversation rather than consuming sustenance. In order to impress Anatevka with his optimal ordering skills, he'd like to minimize the length of the largest continuous stretch of idle time throughout the dinner.
Input
Line 1: 1 integer, $N$
Line 2: $N$ integers, $W_{1..N}$
Line 3: $N$ integers, $T_{1..N}$
Output
1 integer, the minimal length possible for the longest stretch of idle time throughout the meal, in minutes
Example
Input:
3
1 5 6
4 2 3
Output:
4
Explanation of Sample:
Brian's optimal strategy is to order dish 3, then 2, then 1. These dishes will then arrive 4, 7, and 10 minutes into the dinner, respectively. The longest stretch of idle time is then 4 minutes long.
As a further example, if Brian were to order dish 3, then 1, then 2, the last 2 dishes would both arrive 9 minutes into the dinner, with dish 2 being held up by dish 1. | 33,259 |
A Romantic Movie Outing (RMOVIE)
Brian the Computer Science Nerd is going on a date with his girlfriend, Anatevka! His romantic location of choice is a movie theatre - but not an IMAX theatre, of course, as that would be far too expensive.
This theatre has $10^9$ rows of $1000$ seats each, which are initially empty. The rows are numbered $1..10^9$ starting from the one closest to the screen, and the seats in each row are numbered $1..1000$ from left to right. Seat $c$ in row $r$ is denoted as seat ($r$, $c$). Seats in rows $1..L$ ($1 \leq L \leq 1000$) are considered to be "close" to the screen, while seats in further rows are considered to be "far".
Over the course of $T$ ($1 \leq T \leq 500,000$) minutes before the movie starts, a number of events occur. During the $i$th minute, either a person enters and sits in the empty seat ($R_i$, $C_i$), the person sitting in the occupied seat ($R_i$, $C_i$) leaves, or Anatevka suggests that she and Brian take seats ($R_i$, $C_i$) and ($R_i$, $C_i+1$). The type of the $i$th event is represented by the character $E_i$, with $E_i =$ "
E
" indicating a person entering, $E_i =$ "
L
" indicating a person leaving, and $E_i =$ "
S
" indicating a seating suggestion. All seats involved in the events are valid seats inside the theatre, and every seat that Anatevka suggests will be "close", as she believes that they're the best.
Every time Anatevka makes a suggestion, Brian must, of course, analyze its quality. If either of the two seats she suggests are already occupied, he should explain that her recommendation is invalid with a simple "No". Otherwise, he'd like to calculate the total inconvenience of both seats in such an arrangement. The inconvenience of sitting in seat ($r$, $c$) is the number of occupied seats in its field of vision (excluding itself). The field of vision of seat ($r$, $c$) includes all seats which are no further than it from seat ($1$, $c$) by Manhattan distance, as shown below (with the "S" representing a suggested seat, and an "F" representing a seat within its field of vision):
After all of the events have taken place, the movie is about to start, and a final decision must be made on where to sit - and Brian will handle that. He concludes that seats that are "far" are clearly superior (as they offer a broader view of the screen), and he knows that the point of going to the movies is to have an optimal viewing experience, so selecting two adjacent seats is certainly not mandatory. As such, he'd like to determine the minimum total inconvenience for any two "far", unoccupied seats in the theatre. Note that, if one of the chosen seats is in the other's field of vision, this does not count towards its inconvenience - it's only determined by other people sitting in the theatre.
Input
First line: 2 integers, $L$ and $T$
Next $T$ lines: 1 character, $E_i$, and 2 integers, $R_i$ and $C_i$, for $i = 1..T$
Output
1 line for each of Anatevka's suggestions: If the suggestion is invalid, the string "No" - otherwise, the total inconvenience of the two suggested seats
Final line: The minimum total inconvenience of any pair of "far", unoccupied seats
Example
Input:
3 7
E 1 2
E 2 5
S 3 3
E 2 3
L 2 5
S 1 3
S 2 2
Output:
3
0
No
0
Explanation of Sample
When Anatevka makes her first suggestion, the front 3 rows and leftmost 5 columns of the theatre look as follows (where a "P" represents a person, and an "S" represents one of the suggested seats):
The person sitting in seat ($1$, $2$) is in the field of vision of both suggested seats, while the person sitting in seat ($2$, $5$) is only in the way of the right one. As such, the total inconvenience of the two seats is $1+2=3$.
The second suggestion is shown below:
These two seats aren't obstructed by any people, so their total inconvenience is $0$. The final suggestion is invalid, as one of its two seats (seat ($2$, $3$)) is already occupied.
Finally, Brian can easily select two "far" which each have inconvenience $0$, as the theatre has $10^9-3$ "far" rows with $1000$ seats each, and most are far from the two people setting in the theatre after the last event. For example, he might choose to take seat ($4$, $6$), while recommending that Anatevka enjoy the view from seat ($100$, $1000$). | 33,260 |
Land Acquisition (ACQUIRE)
Gold Problem Land Acquisition [Paul Christiano, 2007]
Farmer John is considering buying more land for the farm and has
his eye on N (1 ≤ N ≤ 50,000) additional rectangular plots, each
with integer dimensions (1 ≤ width
i
≤ 1,000,000; 1 ≤ length
i
≤ 1,000,000).
If FJ wants to buy a single piece of land, the cost is $1/square
unit, but savings are available for large purchases. He can buy
any number of plots of land for a price in dollars that is the width
of the widest plot times the length of the longest plot. Of course,
land plots cannot be rotated, i.e., if Farmer John buys a 3×5 plot
and a 5×3 plot in a group, he will pay 5×5 = 25.
FJ wants to grow his farm as much as possible and desires all the
plots of land. Being both clever and frugal, it dawns on him that
he can purchase the land in successive groups, cleverly minimizing
the total cost by grouping various plots that have advantageous
width or length values.
Given the number of plots for sale and the dimensions of each,
determine the minimum amount for which Farmer John can purchase all
Input
Line 1: A single integer: N
Lines 2..N+1: Line i+1 describes plot i with two space-separated
integers: width
i
and length
i
Output
Line 1: The minimum amount necessary to buy all the plots.
Sample
Input:
4
100 1
15 15
20 5
1 100
Output:
500
Explanation
There are four plots for sale with dimensions as shown.
The first group contains a 100×1 plot and costs 100. The next group
contains a 1×100 plot and costs 100. The last group contains both the 20×5
plot and the 15×15 plot and costs 300. The total cost is 500, which is
minimal. | 33,261 |
Ancient Aliens (BFDIV)
Everyone knows that our human ancestors relied on extraterrestrial beings to teach them about science and technology. After helping us build pyramids and chart the stars, our alien mentors decided we needed some time to grow in isolation, so they took some dolphins and left to colonise another planet. Just before leaving, though, they gave us instructions on how to contact them in case of an emergency, such as global warming, nuclear holocaust, or a shortage of fish. The intergalactic telephone they designed consisted of a large golden box powered by alien arc technology. It was entrusted to the United Anarchist Alliance, but was lost when they went to war with the Unified Anarchist League after unsuccessful negotiations to decide which name was more logical for anarchists to call themselves. It remained lost for several centuries at the bottom of a lake until renowned archaeologists Indiana Serkis and Meronym Spader discovered it by chance during a fishing trip. Upon opening the box and pressing the large red button they found inside, an ancient alien immediately appeared and asked them deep, probing questions to determine whether humanity had advanced to the point where the aliens could come back to Earth and chill with us. Among other things, the aliens asked Indiana what his favorite color was, and what the result would be if 38157917385 were divided by 53387519, expressed as quotient and remainder. Since mathematics was never Indiana’s or Meronym’s strong suit, they’ve asked you to write a program for them to perform such computations automatically. They have a computer with them that only understands one language, but they assure you that despite its simplicity the language is Turing complete and perfectly capable of computing the desired quantities efficiently.
Note:
You can use any programming language you want, as long as it is brainf**k.
Input
The first line contains an integer
T
(1 ≤
T
≤ 1000). Then follow
T
lines, each containing integers
x
(0 ≤
x
≤ 10^20) and
y
(1 ≤
y
≤ 10^20) separated by a single space. Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.
Output
T
lines containing the quotient and remainder of
x
divided by
y
, separated by a space.
Example
Input:
5
0 42
42 42
123 45
12 345
10000 42
Output:
0 0
1 0
2 33
0 12
238 4
Additional Info
There are two randomly generated data sets, one with
T
=1000 and the other with
T
=500. The average number of digits in
x
is about 13.5, the average number of digits in
y
is about 8, and the probability that the quotient is nonzero is about 0.82.
My solution at the time of publication has 1516 bytes (not golfed) and runs in 0.14s with 1.9M memory footprint. | 33,262 |
Farmer Joe (BFMUL)
Farmer Joe is a strange fellow indeed. He owns a rare breed of cow that eats chocolate and produces chocolate milk, and each cow has exactly
L
legs. Lately, Joe has been suffering from sore feet, and his intuition tells him that it must be from the chocolate milk. The cows, he suspects, are in pain from stepping on sharp pebbles while crossing the road with chickens in their bare hooves. Naturally, they are transferring their pain karmically through the milk. So he has taken it upon himself to make proper hoofwear for all of them. As he lives at the top of an ivory tower, he finds it most convenient to count their heads. (Each cow has exactly one head.) Joe would like to know how many shoes he must make given that he has counted
H
heads, and in fact he wrote a program for just this purpose but can’t seem to find it. The program is written for a special computer that he constructed while he was writing his dissertation on Turing machines. He has asked for your help in replacing his program. Please help him quickly, so his cows can suffer as little as possible.
Note:
You can use any programming language you want, as long as it is brainf**k.
Input
The first line contains an integer
T
(1 ≤
T
≤ 1000). Then follow
T
lines, each containing integers
L
and
H
(0 ≤
L
,
H
≤ 10^20) separated by a single space. Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.
Output
T
lines containing the number of shoes Farmer Joe must make.
Example
Input:
5
0 0
0 42
42 0
42 42
12345 67890
Output:
0
0
0
1764
838102050
Additional Info
There are two randomly generated data sets, one with
T
=1000 and the other with
T
=500.
L
and
H
are generated independently, and the average number of digits in either is about 11.
My solution at the time of publication has 410 bytes (not golfed) and runs in 0.27s with 1.8M memory footprint. | 33,263 |
One Good Base Deserves Another (BFBASE)
Basil and Blaise are very interested in manufacturing sodium hydroxide, ammonia, and other bases. They currently work out of an old basement but are itching to establish a new home base at the base of a tall mountain overlooking the bay. They’re meeting with their real estate agent, Bane, to look for a building large enough to house their basic operations. Bane seems like a trustworthy fellow, based on his professional manner and charming smile, but he secretly harbors base intentions. He uses a special bank, Hexcorp, that conducts all of its business in hexadecimal. He is extra careful to make sure all the figures in his contracts use only the digits 0 through 9, even though they are in hexadecimal, in the hopes that his clients will unwittingly agree to his inflated prices so he can keep a hefty share for himself. He has included a notice about his unusual choice of numeric base in the very fine print of his contracts, to protect himself legally and cover all bases.
Fortunately, Basil and Blaise always read contracts very carefully before signing them, and the strange notice catches their attention. But they don’t know anything about converting numbers between bases, since before turning to chemistry Basil was a professional baseball player and Blaise was an aspiring bass guitarist, and neither has had much mathematical training. Please help them avoid getting scammed by sending them a program that will allow them to take an integer in one base and convert it into another base. But be careful: Bane has a deep network of spies, and if they intercept your correspondence, Bane may take drastic action. Luckily, his spies don’t understand brainf**k, so you can safely send them anything in that language.
Note:
You can use any programming language you want, as long as it is brainf**k.
Input
For clarity, all integers in this section are given in decimal.
The first line contains an integer
T
(1 ≤
T
≤ 1000) expressed in decimal. Then follow
T
lines, each containing 3 space-separated integers:
B1
and
B2
(2 ≤
B1
,
B2
≤ 35) expressed in base
36
, followed by
N
(0 ≤
N
≤ 35^35) expressed in base
B1
. For bases greater than 10, only uppercase letters are used.
Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.
Output
T
lines containing
N
expressed in base
B2
. For bases greater than 10, only uppercase letters are allowed.
Example
Input:
9
F A 50000
A 2 42
2 A 101010
2 Z 1011011101111011111
7 8 0
Z 7 YWX123ABC
Y I ABCDEFG
I Y ABCDEFG
Y Y ABCDEFG
Output:
253125
101010
42
8QQF
0
22400453332065605
1816CB9F4
7X2J66
ABCDEFG
Additional Info
There are two randomly generated data sets, one with
T
=1000 and the other with
T
=500.
B1
and
B2
are generated independently, and the average value of either is about 18.5. The average number of digits in
N
when expressed in decimal is about 14.
My solution at the time of publication has 678 bytes (not golfed) and runs in 3.71s with 1.8M memory footprint. | 33,264 |
A Kleene Implementation (BFREGEX1)
Thor, the Norse god of thunder, was shopping for groceries when he noticed a sale on Kleenex brand tissues. This got him thinking about Kleene’s recursion theorem and its application to quines in functional programming languages. As this gave him a headache, he instead turned his attention to how one might recognise regular expressions with Kleene stars on a Turing machine. Unfortunately, this just made his headache worse. So he took out a slip of paper, jotted down a brainf**k program to handle regular expressions containing Kleene plusses, paid for his groceries, and congratulated himself on a job well done.
Note:
You can use any programming language you want, as long as it is brainf**k.
Input
The first line contains an integer
T
(1 ≤
T
≤ 1000). Then follow
T
test cases.
For each test case: The first line contains a regular expression
P
(1 ≤ |
P
| ≤ 30). The next line contains an integer
Q
(1 ≤
Q
≤ 10). Then follow
Q
lines, each containing a string
S
(1 ≤ |
S
| ≤ 100). Finally, there is an empty line at the end of each test case.
Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.
All regular expressions are guaranteed to be valid; in particular,
P
may not start with a plus, and it may not contain two consecutive plusses.
P
is a string over the alphabet {a, b, c, d, +}, and
S
is a string over the alphabet {a, b, c, d}.
Output
T
lines each containing a string of length
Q
. The
i
th character of the string indicates whether
S
is in the regular language defined by
P
: 'Y' for a match, and '.' otherwise. Note that we are concerned whether
P
matches
S
, as opposed to a substring of
S
. In other words, we could insert '^' at the beginning of
P
and '$' at the end, and then test for a match using e.g. m// in Perl. See the example for further clarification.
Example
Input:
3
a
2
a
aa
a+
2
a
aa
a+bc
6
abbacadabba
aaaabc
abc
bc
abcd
babc
Output:
Y.
YY
.YY...
Additional Info
There are two randomly generated data sets, one with
T
= 1000 and the other with
T
= 500. The average value of
Q
is about 6, the probability of a match is about 0.25, the average length of
P
is about 14, and the average length of
S
is about 27.
My solution at the time of publication has 803 bytes (not golfed) and runs in 0.20s with 2.6M memory footprint. | 33,265 |
play with prime numbers (I) (POP1)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
We define here a new prime number called prime of primes number (POP) is a prime number that consist of other prime numbers less than this number.
For example: 1013 consist of 101 and 3 and both are primes.
Note
: 2003 is not POP because leading zero not allowed.
The POP number must contain more than or equal two primes , and overlapping not allowed.
Input
The first line contains an integer T specifying the number of test cases. (T <= 10^4) followed by T lines, each line contains an integer m number 0 <= m <= 10^9.
Output
For each test case print single line contain the first integer greater than or equal to m and is POP.
Example
Input:
3
10
100
1000
Output:
23
113
1013
after solving this you can try
http://www.spoj.com/problems/POP2/ | 33,266 |
play with prime numbers (II) (POP2)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
We define here a new prime number called prime of primes number (POP) is a prime number that consists of other prime numbers less than this number.
Example:
1013 consists of 101 and 3 and both are prime.
Notes
: 2003 is not POP because leading zeros are not allowed.
The POP numbers must contain more than or equal two primes, and overlapping is not allowed .
Input
The first line contains an integer T specifying the number of test cases. (T <= 200)
Followed by T lines, each line contains an integer m number 0 <= m <= 10
18
.
Output
For each test case print single line contain the first integer greater than or equal to m and is (POP) .
Example
Input
3
10
100
1000
Output
23
113
1013
After solving this you can try
http://www.spoj.com/problems/POP3/ | 33,267 |
play with prime numbers (III)(hard ) (POP3)
A prime number is a natural number greater than 1 that has no positive divisors
other than 1 and itself.
we define here a new prime number called prime of primes number (POP) is
a prime number that consist of other prime numbers less than this number.
example:
1013 consist of 101 and 3 and both are primes.
notes
:
2003 is not POP because leading zero not allowed.
The POP number must contain more than or equal two primes, and overlapping not allowed.
Input
The first line contains an integer T specifying the number of test cases (T <= 200) followed by T lines,
each line contains an integer m number 0 <=m <= 10^27.
Output
For each test case, print a single line containing the first integer greater than or equal to m and is (POP).
Example
Input:
3
10
100
1000
Output:
23
113
1013
time limit has been changed and all solution was rejudged. | 33,268 |
primes triangle (I) (PTRI)
The primes triangle is a triangle that contain all prime numbers .
2
3 5
7 11 13
17 19 23 29
...
Your task is very easy given an integer from 1 to 10
8
print its place in the primes triangle.
Input
In the first line integer 1 ≤ T ≤ 10
5
, followed by T lines each line contain integer 1 ≤ n ≤ 10
8
.
Output
One line contain pair of integers i, j, where i is the row number and j is the column number, 1 base. Or -1 if n is not found in the primes triangle.
Example
Input:
3
3
23
4
Output:
2 1
4 3
-1
If you find Time limit is small here you can solve the tutorial version here:
PTRI2
. | 33,269 |
primes triangle (II) (PTR2)
Primes triangle is a triangle that contain all prime numbers.
2
3 5
7 11 13
17 19 23 29
... ... ...
Your task is very easy given an integer from 1 to 10
9
prints its place in the primes triangle.
Input
in the first line integer 1 ≤ T ≤ 10
4
, followed by T lines each line contain integer 1 ≤ n ≤ 10
9
.
Output
One line contain pair of integers i and j, where i is the row number and j is the column number, 1 based. Or -1 if n is not found in the primes triangle.
Example
Input:
3
3
23
4
Output:
2 1
4 3
-1
if you find time limit is small, you can solve the tutorial version here:
www.spoj.com/problems/PTR22/ | 33,270 |
MAXIMUM RARITY (SBO)
Given a sequence of numbers, each number between 1 and 100000 (inclusive), find the contiguous subsequence with maximum rarity.
The rarity of a sequence is defined as the count of numbers which appear only once in that sequence. For example, let's consider the following sequence:
1 1 2 5 1 16 5
The rarity of the subsequence 1 1 2 5 is 2. This is because 2 and 5 are the only numbers which appear just once. 1 appears twice in the sequence, hence doesn't contribute to its rarity. The rarity of subsequence 1 16 5 is 3 as each of the numbers appears only once. The maximum rarity achieved by any contiguous subsequence in the sequence 1 1 2 5 1 16 5 is 4. This is the rarity of 2 5 1 16.
Your task is to find the contiguous subsequence with maximum rarity and output that rarity value. You don't have to output the subsequence itself.
Input
The first line of input will contain an integer N. N is the count of numbers in the input sequence.
1 <= N <= 500000.
The next line will contain the sequence of numbers. Each number in the sequence is an integer between 1 and 100000.
Output
The maximum rarity that any contiguous subsequence possesses.
Example
Input 1:
7
1 1 2 5 1 16 5
Output 1:
4
Input 2:
3
1 2 3
Output 2:
3
Input 3:
10
2 1 4 1 5 6 7 1 8 2
Output 3:
6
Input 4:
20
3 4 14 14 9 7 11 7 15 13 9 9 14 9 13 10 13 9 5 4
Output 4:
7
Explanation
Input 2:
The maximum rarity is achieved by the sequence itself.
Input 3:
The maximum rarity is achieved by the subsequences 1 4 1 5 6 7 1 8 2, 4 1 5 6 7 1 8 2 and 5 6 7 1 8 2. All the three contiguous subsequences have rarity 6.
Input 4:
The maximum rarity is achieved by the subsequence 11 7 15 13 9 9 14 9 13 10 13 9 5 4. This sequence has 7 numbers which appear only once in it, i.e., 11, 7, 15, 14, 10, 5, 4. | 33,271 |
Minimum Cost (MC)
Problem Statement
Given two string
S
and
T
. You can delete a character from
S
with cost 15 and a Character
T
with cost 30. Your goal is to make the string equal (same). It is not mandatory to delete character.
For example: S =
aXb
and T =
Yab
. Now, if we delete X from S and Y from T, then total cost = 15 + 30 = 45.
And S and T will become
ab
.
Another example: S =
ab
, T =
cd
, Now total cost = 15 + 15 + 30 + 30 = 90.
Another example: S =
abcd
, T =
acdb
, Now total cost = 15 + 30 = 45.
Input
Input consists of pairs of lines. The first line of a pair contains the first string
S
and the second line contains the second string
T
. Each string is on a separate line and consists of at most 1,000 characters . The end of input occurs when the first sequence starts with an "
#
" character (without the quotes).
Output
For each subsequent pair of input lines, output a line containing one integer number which the minimum cost to make the string equal (same).
Sample Input/Output
Sample Input
Sample Output
axb
yab
ab
cd
ko
p
abcd
acdb
#
45
90
60
45
___________________________________________________________________________________________________________
Problem Setter: Shipu Ahamed, Dept. of CSE
Bangladesh University of Business and Technology (BUBT) | 33,272 |
David and his Obsession (PUCMM009)
You are walking by an empty corridor at PUCMM. All around you are arithmetic expressions written on the walls and on the floor. You find it odd and quickly realize all these expressions seem to be failed attempts to solve a problem. As you read by, you hear a voice coming from one of the classrooms that is whispering “I do not see it! I do not see it!” You walk to the classroom and find David rolling on the floor in frustration.
“What’s going on, David? you ask.
“The answer.. I do not see! Do you see?” replies David.
“What answer?” you ask him.
“Professor Olson gave me this problem and … I do not see.”
“Ok. What about you stand up and describe the problem to me?” you ask again.
“Well, OK. You are pretty smart yourself. Imagine ten slips of paper bearing the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 are put into a hat. 5 slips are drawn at random and laid out in a row in the order in which they were drawn.” He sighs deeply. “What is the probability that the 5-digit number so formed is divisible by 495?”
On your backpack there is a laptop. Help him. Write an algorithm that solves the problem.
Input
There is no input for this problem.
Output
Print in a single line the answer as a fraction expressed in its lowest terms.
Sample cases
There are no sample cases for this problem.
Notes
In case you need this, the greatest common divisor of (a, b) is defined recursively as follows:
gcd(a, b) = b if a == 0, otherwise gcd = gcd(b
mod
a, a). | 33,273 |
Luis Quest (VPL2_AA)
Luis is playing his old metroid game. Just a little while ago he pass trough a scenario where the room was filled with some amoeba-like creatures. The room started with some initial number of creatures, but they multiply their selves very quickly, because their growth rate is proportional to the number of creatures at a certain time. Luis took note about this fact, he wrote the number of creatures at the initial time, and then, after wait t time units, he wrote the new amount. Now Luis wants to know, for a certain number of creatures p, the exact time he has to be in the room to see that amount.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
For each test case, there will be 2 lines, the first one will contain 4 integers, p0, p1, t and p. These numbers represents the initial amount of creatures, the second amount of creatures, the time units that Luis waited to see that change, and the number of creatures that Luis wants to see.
Output
For each input case you must print a single line containing the string "
Scenario #i:
" where i is the number of the test case (starting at one), and then the answer to the problem rounded to two decimal places. There will always be an answer.
Example
Input:
4
10 15 3 15
10 15 3 20
5 12 2 50
5 12 2 7
Output:
Scenario #1: 3.00
Scenario #2: 5.13
Scenario #3: 5.26
Scenario #4: 0.77
Constraints
1 ≤ T, p0, p1, t, p ≤ 100 | 33,274 |
Betos Quest (VPL2_AB)
Beto is playing a game called "Impossible Mission" and he is getting very angry. He got completely stuck on the final mission. Here's what's the mission is about: Ethan Hunt must simply walk from a given start field to an end one. Hindering his progress, there are fake floor tiles that he must avoid. However that's not all, there are cameras everywhere!
Camera
i
has range
Ri
and can be directed in four cardinal directions. It will scan
Ri
fields in a given direction, not including field were it's placed itself. Every second camera will rotate 90 degrees clock-wise.
Ethan can move only in the four cardinal directions. He must make exactly one move every second (he can't stand in place). In addition, Ethan Hunt can use a special suit that makes him invisible to the cameras, even if he is in the range of multiples cameras. Unfortunately, as everything in the IMF, the suit is a prototype and tends to fail after a second of use. That's ́why Ethan has C suits that he will be able to use. It's possible Ethan will start on a field screened by a camera. In such a case he must use a suit. If he doesn't have one, the game is already lost. Also for final position, you must use a suit to shield against screening before exiting, if you are spotted by a camera.
Your mission, if you choose to accept it, is to help Beto to succeed in the game by telling him whether if it is possible or not to cross the maze. If it is possible, give Beto a clue and output the minimum steps needed to solve the problem.
Input
The first line contains an integer T, which specifies the number of test cases. Then the descriptions of T test cases follow.
For each case, first line will contain four integers
N
,
M
,
K
,
C
denoting the height and the width of the matrix, the number of cameras and the number of camouflage suits Ethan has.
Next N lines will follow with M characters each. The ’#’ character denotes a fake floor and Ethan must avoid it. The ’.’ denotes a normal floor. Note than a fake floor will only block Ethan and not a camera field of view.
Next K lines will follow with the description of the cameras. Each line will consist on four integers, denoting respectively the row and the column where the camera is (both 0-based), the range
Ri
of the camera and it's initial direction
Di
. 0 means that the camera is pointing to north, 1 east, 2 south and 3 west.
Final two lines will contain two integers each, denoting the starting point and the ending point of Ethan Hunt. For both lines, first integer describes the row and second the column, both 0-based. It is guaranteed that Ethan won't start or be directed to a fake floor.
Output
For each input case, you must print a single line. The string "Scenario #i: " where i denotes the case you are analyzing (starting by 1), followed by the minimum number of steps that Ethan must make in order to reach his destination. If it is impossible, print -1.
Example
INPUT
OUTPUT
2
5 4 3 0
....
.#..
..#.
....
....
0 3 4 2
2 1 4 0
4 0 1 0
0 0
4 3
3 3 2 0
...
...
...
0 2 1 2
2 0 1 3
0 0
2 2
Scenario #1: 7
Scenario #2: -1
Constraints - Subtask 1 (30%)
1 ≤ T ≤ 30
1 ≤ N ,M ≤ 100
1 ≤ K ≤ 100
0 ≤ C ≤ 0
1 ≤ Rk ≤ 100
Constraints - Subtask 2 (30%)
1 ≤ T ≤ 20
1 ≤ N ,M ≤ 100
1 ≤ K ≤ 100
0 ≤ C ≤ 10
1 ≤ Rk ≤ 100
Constraints - Subtask 3 (40%)
1 ≤ T ≤ 10
1 ≤ N ,M ≤ 1000
1 ≤ K ≤ 1000
0 ≤ C ≤ 10
1 ≤ Rk ≤ 1000 | 33,275 |
Primos Quest (VPL2_AC)
Primo is playing Guitar Hero, but he has been playing it for quite long, and his hand is a little tired. He knows that for every change between colors his energy goes down. The colors of the guitar are ordered like this: Green, Red, Yellow, Blue and Orange. The energy to change from playing a color A, to a color B, is the absolute difference of the distance between them, by example, changing from Red to Yellow, costs 1 unit of energy, and changing from Blue to Green costs 3 units of energy. Primo knows that he has exactly C units of energy left, and he also know the colors of the notes from a random song. Help him find out the maximum number of notes in a row that he can play on this song.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
For each test case you will have a single line containing an integer C, representing the energy left of Primo, and a string S, representing the colors and the order of the notes from the song. Each character in S will be ’G’ for Green, ’R’ for Red, ’Y’ for Yellow, ’B’ for Blue or ’O’ for Orange.
Output
For each input case you must print Scenario #i: where i is the number of the test case (starting at one), and then the answer to the problem.
Sample
Input
3
0 OORRBYYYGG
1 RRORGRRRBOY
3 RRRORORRRR
Output
Scenario #1: 3
Scenario #2: 4
Scenario #3: 5
Constraints
Constraints - 40%
1 ≤ T ≤ 100
0 ≤ C, |S| ≤ 1000
Constraints - 60%
1 ≤ T ≤ 100
0 ≤ C, |S| ≤ 1000000 | 33,276 |
Davids Quest (VPL2_AD)
David is playing minesweeper and he really wants to break his record at the game. The only way to achieve this is by cheating! As he is a fast clicker (or at least he believes that), he wants to know how much clicks must be given in order to solve the puzzle.
I case you never played minesweeper, here are some basic rules. You are given a rectangular map divided into square cells. At the start of the game, all the cells are hidden. Under some of them there are mines. You are required to uncover all cells WITHOUT mines (we will call them safe cells). If you try to uncover a mine, the game is over and you lost. On safe cells there are hints to help you along the way. They contain numbers that indicate how many mines are hidden on the 8 adjacent cells (less in case of border cells). So we have numbers 1 to 8 and those can be uncovered with a single click. If there are no neighboring mines the filed is simply empty. In addition, if you will uncover this empty cells, all its neighboring will be uncovered automatically. This effect is also recursive, so can uncover a bigger chunk with one click, if there are more connected empty cells.
David knows everything about the puzzle: where the mines are located and thus he can also deduce the number hints on others cells.
Input
The first line contains an integer T, the number of test cases. Description of T testcases follow. Every case with two numbers N and M: denoting the height and the width of the puzzle. Then N lines with M characters each. Characters are as follows:
'-'
: denotes an empty cell,
'*'
: denotes a mine,
'1'-'8'
: Numbers
i
denotes that there is
i
mines adjacent to the current one.
Output
For each input case you must print a single line. The string "Scenario #i: " where i denotes the case you are analyzing (starting with 1), followed by the number of clicks that must be given in order to uncover all safe cells.
INPUT
OUTPUT
3
3 2
*2
2*
11
3 3
***
232
---
8 8
1*1-----
111-1221
----1**1
----2331
11--1*32
*1--13**
11---2**
-----13*
Scenario #1: 4
Scenario #2: 1
Scenario #3: 9
Constraints - Subtask 1 (40%)
1 ≤ T ≤ 10
1 ≤ N ≤ 128
1 ≤ M ≤ 128
Constraints - Subtask 2 (60%)
1 ≤ T ≤ 10
1 ≤ N ≤ 2048
1 ≤ M ≤ 2048 | 33,277 |
Swap (Easy - Level 2) (SWAP_ESY)
Let's play with sequence of non negative integer. Given two sequence of
n
non negative integers (a
1
, a
2
... a
n
) and (b
1
, b
2
... b
n
). Both sequence has maximum element less than
k
, max(a
1
,
a
2
... a
n
) <
k
and max(b
1
, b
2
... b
n
) <
k
. The game rule is you can edit both sequence with this operaton: swap a
i
and b
i
with 1 ≤
i
≤
n
, and the goal is to make sequence
a
and
b
become increasing sequence: a
i
≤ a
j
if and only if
i
≤
j
and b
i
≤ b
j
if and only if
i
≤
j
. But not all initial sequence
a
and
b
can be solved.
For example (2, 0) and (0, 1) is a pair of sequence that can't be solved:
If you don't swap any element, you have (2, 0) and (0, 1), but sequence (2, 0) is not increasing.
If you swap first element only, then the pair become like this (0, 0) and (2, 1), sequence (2, 1) is not increasing.
If you swap second element only, then the pair become like this (2, 1) and (0, 0), again (2, 1) is not increasing.
If you swap both element, thrn the pair become like this (0, 1) and (2, 0), again (2, 0) is not increasing
So it's impossible to solve if initial sequence is (2, 0) and (0, 1), because all possible move can't make both sequence become increasing.
Now given
n
and
k
, your task is to compute number of different pair of initial sequence (
a
,
b
) that can be solved with game described above.
Input
First line there is an integer
T
denoting number of test case, then
T
test cases follow.
For each case, there are two integers
n
and
k
writen in one line, separated by a space.
Output
For each case, output number of different pair of initial sequence (
a
,
b
), since the answer can be large, output the answer modulo 10
9
+7.
Constraints
0 <
T
≤ 10
5
0 < min(
n
,
k
) ≤ 2
0 < max(
n
,
k
) < 10
9
Example
Input:
6
2 1
1 2
1 3
2 2
3 2
2 3
Output:
1
4
9
11
26
46
Explanation
Here is list of all possible pair of initial sequence (
a
,
b
) on each case:
Case 1: {[(0, 0), (0, 0)]}
Case 2: {[(0), (0)], [(0), (1)], [(1), (0)], [(1), (1)]}
Case 3: {[(0), (0)], [(0), (1)], [(0), (2)], [(1), (0)], [(1), (1)], [(1), (2)], [(2), (0)], [(2), (1)], [(2), (2)]}
Case 4: {[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (1, 1)], [(0, 1), (0, 0)], [(0, 1), (0, 1)], [(0, 1), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (0, 1)], [(1, 1), (0, 0)], [(1, 1), (0, 1)], [(1, 1), (1, 1)]}
Case 5: {[(0, 0, 0), (0, 0, 0)], [(0, 0, 0), (0, 0, 1)], [(0, 0, 0), (0, 1, 1)], [(0, 0, 0), (1, 1, 1)], [(0, 0, 1), (0, 0, 0)], [(0, 0, 1), (0, 0, 1)], [(0, 0, 1), (0, 1, 0)], [(0, 0, 1), (0, 1, 1)], [(0, 0, 1), (1, 1, 0)], [(0, 0, 1), (1, 1, 1)], [(0, 1, 0), (0, 0, 1)], [(0, 1, 0), (1, 0, 1)], [(0, 1, 1), (0, 0, 0)], [(0, 1, 1), (0, 0, 1)], [(0, 1, 1), (0, 1, 1)], [(0, 1, 1), (1, 0, 0)], [(0, 1, 1), (1, 0, 1)], [(0, 1, 1), (1, 1, 1)], [(1, 0, 0), (0, 1, 1)], [(1, 0, 1), (0, 1, 0)], [(1, 0, 1), (0, 1, 1)], [(1, 1, 0), (0, 0, 1)], [(1, 1, 1), (0, 0, 0)], [(1, 1, 1), (0, 0, 1)], [(1, 1, 1), (0, 1, 1)], [(1, 1, 1), (1, 1, 1)]}
Case 6: {[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (0, 2)], [(0, 0), (1, 1)], [(0, 0), (1, 2)], [(0, 0), (2, 2)], [(0, 1), (0, 0)], [(0, 1), (0, 1)], [(0, 1), (0, 2)], [(0, 1), (1, 0)], [(0, 1), (1, 1)], [(0, 1), (1, 2)], [(0, 1), (2, 2)], [(0, 2), (0, 0)], [(0, 2), (0, 1)], [(0, 2), (0, 2)], [(0, 2), (1, 0)], [(0, 2), (1, 1)], [(0, 2), (1, 2)], [(0, 2), (2, 0)], [(0, 2), (2, 1)], [(0, 2), (2, 2)], [(1, 0), (0, 1)], [(1, 0), (0, 2)], [(1, 1), (0, 0)], [(1, 1), (0, 1)], [(1, 1), (0, 2)], [(1, 1), (1, 1)], [(1, 1), (1, 2)], [(1, 1), (2, 2)], [(1, 2), (0, 0)], [(1, 2), (0, 1)], [(1, 2), (0, 2)], [(1, 2), (1, 1)], [(1, 2), (1, 2)], [(1, 2), (2, 1)], [(1, 2), (2, 2)], [(2, 0), (0, 2)], [(2, 1), (0, 2)], [(2, 1), (1, 2)], [(2, 2), (0, 0)], [(2, 2), (0, 1)], [(2, 2), (0, 2)], [(2, 2), (1, 1)], [(2, 2), (1, 2)], [(2, 2), (2, 2)]}
Other Info
Test case (
n
and
k
) is generated randomly using this rule:
Probability that
n
>
k
or
n
≤
k
is ~50% each.
Maximum
n
and
k
is random log-uniform.
Minimum
n
and
k
is random uniform.
Click here if you want to know my program speed and other detail.
Time limit >100× my program top speed.
See also:
Another problem added by Tjandra Satria Gunawan | 33,278 |
Swap (Medium - Level 200) (SWAP_MED)
Let's play with sequence of non negative integer. Given two sequence of
n
non negative integers (a
1
, a
2
... a
n
) and (b
1
, b
2
... b
n
). Both sequence has maximum element less than
k
, max(a
1
,
a
2
... a
n
)<
k
and max(b
1
, b
2
... b
n
)<
k
. The game rule is you can edit both sequence with this operation: swap a
i
and b
i
with 1≤
i
≤
n
, and the goal is to make sequence
a
and
b
become increasing sequence: a
i
≤a
j
if and only if
i
≤
j
and b
i
≤b
j
if and only if
i
≤
j
. But not all initial sequence
a
and
b
can be solved.
For example (2, 0) and (0, 1) is a pair of sequence that can't be solved:
If you don't swap any element, you have (2, 0) and (0, 1), but sequence (2, 0) is not increasing.
If you swap first element only, then the pair become like this (0, 0) and (2, 1), sequence (2, 1) is not increasing.
If you swap second element only, then the pair become like this (2, 1) and (0, 0), again (2, 1) is not increasing.
If you swap both element, then the pair become like this (0, 1) and (2, 0), again (2, 0) is not increasing
So it's impossible to solve if initial sequence is (2, 0) and (0, 1), because all possible move can't make both sequence become increasing.
Now given
n
and
k
, your task is to compute number of different pair of initial sequence (
a
,
b
) that can be solved with game described above.
Input
First line there is an integer
T
denoting number of test case, then
T
test cases follow.
For each case, there are two integers
n
and
k
writen in one line, separated by a space.
Output
For each case, output number of different pair of initial sequence (
a
,
b
), since the answer can be large, output the answer modulo 10
9
+7.
Constraints
0 <
T
≤ 10
5
0 < min(
n
,
k
) ≤ 200
0 < max(
n
,
k
) < 10
18
Example
Input:
6
2 1
1 2
1 3
2 2
3 2
2 3
Output:
1
4
9
11
26
46
Explanation
Here is list of all possible pair of initial sequence (
a
,
b
) on each case:
Case 1: {[(0, 0), (0, 0)]}
Case 2: {[(0), (0)], [(0), (1)], [(1), (0)], [(1), (1)]}
Case 3: {[(0), (0)], [(0), (1)], [(0), (2)], [(1), (0)], [(1), (1)], [(1), (2)], [(2), (0)], [(2), (1)], [(2), (2)]}
Case 4: {[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (1, 1)], [(0, 1), (0, 0)], [(0, 1), (0, 1)], [(0, 1), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (0, 1)], [(1, 1), (0, 0)], [(1, 1), (0, 1)], [(1, 1), (1, 1)]}
Case 5: {[(0, 0, 0), (0, 0, 0)], [(0, 0, 0), (0, 0, 1)], [(0, 0, 0), (0, 1, 1)], [(0, 0, 0), (1, 1, 1)], [(0, 0, 1), (0, 0, 0)], [(0, 0, 1), (0, 0, 1)], [(0, 0, 1), (0, 1, 0)], [(0, 0, 1), (0, 1, 1)], [(0, 0, 1), (1, 1, 0)], [(0, 0, 1), (1, 1, 1)], [(0, 1, 0), (0, 0, 1)], [(0, 1, 0), (1, 0, 1)], [(0, 1, 1), (0, 0, 0)], [(0, 1, 1), (0, 0, 1)], [(0, 1, 1), (0, 1, 1)], [(0, 1, 1), (1, 0, 0)], [(0, 1, 1), (1, 0, 1)], [(0, 1, 1), (1, 1, 1)], [(1, 0, 0), (0, 1, 1)], [(1, 0, 1), (0, 1, 0)], [(1, 0, 1), (0, 1, 1)], [(1, 1, 0), (0, 0, 1)], [(1, 1, 1), (0, 0, 0)], [(1, 1, 1), (0, 0, 1)], [(1, 1, 1), (0, 1, 1)], [(1, 1, 1), (1, 1, 1)]}
Case 6: {[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (0, 2)], [(0, 0), (1, 1)], [(0, 0), (1, 2)], [(0, 0), (2, 2)], [(0, 1), (0, 0)], [(0, 1), (0, 1)], [(0, 1), (0, 2)], [(0, 1), (1, 0)], [(0, 1), (1, 1)], [(0, 1), (1, 2)], [(0, 1), (2, 2)], [(0, 2), (0, 0)], [(0, 2), (0, 1)], [(0, 2), (0, 2)], [(0, 2), (1, 0)], [(0, 2), (1, 1)], [(0, 2), (1, 2)], [(0, 2), (2, 0)], [(0, 2), (2, 1)], [(0, 2), (2, 2)], [(1, 0), (0, 1)], [(1, 0), (0, 2)], [(1, 1), (0, 0)], [(1, 1), (0, 1)], [(1, 1), (0, 2)], [(1, 1), (1, 1)], [(1, 1), (1, 2)], [(1, 1), (2, 2)], [(1, 2), (0, 0)], [(1, 2), (0, 1)], [(1, 2), (0, 2)], [(1, 2), (1, 1)], [(1, 2), (1, 2)], [(1, 2), (2, 1)], [(1, 2), (2, 2)], [(2, 0), (0, 2)], [(2, 1), (0, 2)], [(2, 1), (1, 2)], [(2, 2), (0, 0)], [(2, 2), (0, 1)], [(2, 2), (0, 2)], [(2, 2), (1, 1)], [(2, 2), (1, 2)], [(2, 2), (2, 2)]}
Other Info
Test case (
n
and
k
) is generated randomly using this rule:
Probability that
n
>
k
or
n
<=
k
is ~50% each.
Maximum
n
and
k
is random log-uniform.
Minimum
n
and
k
is random uniform.
Click here if you want to know my program speed and other detail.
Explanation about my Algorithm complexity:
My 2.8KB of python 3 code that got AC in 18.7s, the complexity is O(min(
n
,
k
)
3
) "This is direct translation [line by line] of my C code, there are many room for optimisations like fast I/O, data structure, etc"
My 3.7KB of C code that got AC in 6.36s, the complexity is O(min(
n
,
k
)
4
)
My 3.8KB of C code that got AC in 0.53s, the complexity is O(min(
n
,
k
)
3
) "Note that although the size of code is similar, but my O(min(
n
,
k
)
4
) and O(min(
n
,
k
)
3
) code is very different"
To challenge fast language user with O(min(
n
,
k
)
3
) complexity, I made this
Hard version
. For slow language user this medium version will be look like hard version ;-) good luck.
About complexity, I've proved using math that no algo with complexity better than O(min(
n
,
k
)
2
), this is the lower bound. My best algo for now is O(min(
n
,
k
)
3
), this is the upper bound. So the optimal algo lies between that lower and upper bound. I still don't have proof that my algo is optimal, so there is possibility that there is an algorithm that better than O(min(
n
,
k
)
3
).
Time limit ~37× my program top speed.
See also:
Another problem added by Tjandra Satria Gunawan | 33,279 |
Swap (Hard - Level 1000) (SWAP_HRD)
Let's play with sequence of non negative integer. Given two sequence of
n
non negative integers (a
1
, a
2
... a
n
) and (b
1
, b
2
... b
n
). Both sequence has maximum element less than
k
, max(a
1
,
a
2
... a
n
) <
k
and max(b
1
, b
2
... b
n
) <
k
. The game rule is you can edit both sequence with this operation: swap a
i
and b
i
with 1 ≤
i
≤
n
, and the goal is to make sequence
a
and
b
become increasing sequence: a
i
≤ a
j
if and only if
i
≤
j
and b
i
≤ b
j
if and only if
i
≤
j
. But not all initial sequence
a
and
b
can be solved.
For example (2, 0) and (0, 1) is a pair of sequence that can't be solved:
If you don't swap any element, you have (2, 0) and (0, 1), but sequence (2, 0) is not increasing.
If you swap first element only, then the pair become like this (0, 0) and (2, 1), sequence (2, 1) is not increasing.
If you swap second element only, then the pair become like this (2, 1) and (0, 0), again (2, 1) is not increasing.
If you swap both element, then the pair become like this (0, 1) and (2, 0), again (2, 0) is not increasing
So it's impossible to solve if initial sequence is (2, 0) and (0, 1), because all possible move can't make both sequence become increasing.
Now given
n
and
k
, your task is to compute number of different pair of initial sequence (
a
,
b
) that can be solved with game described above.
Input
First line there is an integer
T
denoting number of test case, then
T
test cases follow.
For each case, there are two integers
n
and
k
written in one line, separated by a space.
Output
For each case, output number of different pair of initial sequence (
a
,
b
), since the answer can be large, output the answer modulo 10
9
+7.
Constraints
0 <
T
≤ 10
4
0 < min(
n
,
k
) ≤ 1000
0 < max(
n
,
k
) < 10
1000
Example
Input:
6
2 1
1 2
1 3
2 2
3 2
2 3
Output:
1
4
9
11
26
46
Explanation
Here is list of all possible pair of initial sequence (
a
,
b
) on each case:
Case 1: {[(0, 0), (0, 0)]}
Case 2: {[(0), (0)], [(0), (1)], [(1), (0)], [(1), (1)]}
Case 3: {[(0), (0)], [(0), (1)], [(0), (2)], [(1), (0)], [(1), (1)], [(1), (2)], [(2), (0)], [(2), (1)], [(2), (2)]}
Case 4: {[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (1, 1)], [(0, 1), (0, 0)], [(0, 1), (0, 1)], [(0, 1), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (0, 1)], [(1, 1), (0, 0)], [(1, 1), (0, 1)], [(1, 1), (1, 1)]}
Case 5: {[(0, 0, 0), (0, 0, 0)], [(0, 0, 0), (0, 0, 1)], [(0, 0, 0), (0, 1, 1)], [(0, 0, 0), (1, 1, 1)], [(0, 0, 1), (0, 0, 0)], [(0, 0, 1), (0, 0, 1)], [(0, 0, 1), (0, 1, 0)], [(0, 0, 1), (0, 1, 1)], [(0, 0, 1), (1, 1, 0)], [(0, 0, 1), (1, 1, 1)], [(0, 1, 0), (0, 0, 1)], [(0, 1, 0), (1, 0, 1)], [(0, 1, 1), (0, 0, 0)], [(0, 1, 1), (0, 0, 1)], [(0, 1, 1), (0, 1, 1)], [(0, 1, 1), (1, 0, 0)], [(0, 1, 1), (1, 0, 1)], [(0, 1, 1), (1, 1, 1)], [(1, 0, 0), (0, 1, 1)], [(1, 0, 1), (0, 1, 0)], [(1, 0, 1), (0, 1, 1)], [(1, 1, 0), (0, 0, 1)], [(1, 1, 1), (0, 0, 0)], [(1, 1, 1), (0, 0, 1)], [(1, 1, 1), (0, 1, 1)], [(1, 1, 1), (1, 1, 1)]}
Case 6: {[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (0, 2)], [(0, 0), (1, 1)], [(0, 0), (1, 2)], [(0, 0), (2, 2)], [(0, 1), (0, 0)], [(0, 1), (0, 1)], [(0, 1), (0, 2)], [(0, 1), (1, 0)], [(0, 1), (1, 1)], [(0, 1), (1, 2)], [(0, 1), (2, 2)], [(0, 2), (0, 0)], [(0, 2), (0, 1)], [(0, 2), (0, 2)], [(0, 2), (1, 0)], [(0, 2), (1, 1)], [(0, 2), (1, 2)], [(0, 2), (2, 0)], [(0, 2), (2, 1)], [(0, 2), (2, 2)], [(1, 0), (0, 1)], [(1, 0), (0, 2)], [(1, 1), (0, 0)], [(1, 1), (0, 1)], [(1, 1), (0, 2)], [(1, 1), (1, 1)], [(1, 1), (1, 2)], [(1, 1), (2, 2)], [(1, 2), (0, 0)], [(1, 2), (0, 1)], [(1, 2), (0, 2)], [(1, 2), (1, 1)], [(1, 2), (1, 2)], [(1, 2), (2, 1)], [(1, 2), (2, 2)], [(2, 0), (0, 2)], [(2, 1), (0, 2)], [(2, 1), (1, 2)], [(2, 2), (0, 0)], [(2, 2), (0, 1)], [(2, 2), (0, 2)], [(2, 2), (1, 1)], [(2, 2), (1, 2)], [(2, 2), (2, 2)]}
Other Info
Test case (
n
and
k
) is generated randomly using this rule:
Probability that
n
>
k
or
n
<=
k
is ~50% each.
Maximum
n
and
k
is random log-uniform.
Minimum
n
and
k
is random uniform.
Click here if you want to know my program speed and other detail.
Explanation about my Algorithm complexity:
My 3.8KB of C code with O(min(
n
,
k
)^3) complexity got AC in 32.17s.
Other submission like O(min(
n
,
k
)^4) in fast language, and O(min(
n
,
k
)^3) in slow language is all TLE. That's why this problem has "Hard" label.
Sorry for slow language user, I think it's impossible to solve this problem unless O(min(
n
,
k
)^2) exists. I recommend to try
Medium version
first, or learn fast language :-P
About complexity, I've proved using math that no algorithm with complexity better than O(min(
n
,
k
)^2), this is the lower bound. My best algorithm for now is O(min(
n
,
k
)^3), this is the upper bound. So the optimal algorithm lies between that lower and upper bound. I still don't have proof that my algo is optimal, so there is possibility that there is an algorithm that better than O(min(
n
,
k
)^3).
Btw, if I found around O(min(
n
,
k
)^2) by myself, I'll set "Extreme" version (level 10000+) of this problem. But if there is someone who solve this problem in around O(min(
n
,
k
)^2), of course he/she has honor to set "Extreme" version of this problem.
Time limit ~3× my program top speed.
See also:
Another problem added by Tjandra Satria Gunawan | 33,280 |
Humans Life Code (MOSTYCOD)
Imagine you are a Human Being ..
So you have some parameters , and those paramters contain values.
If you can imagine this,you can understand the Fact that Humans Store Their Parameters
In A Big Array ... (Actually The Array Is Of Size 00963999206048 bit)
[We will not discuss the meaning of the parameters here]
If You want to know what is the value of some parameter
you should go throw your mind .. surfing the internal array until reach the place for the parameter.
The Most Important Thing To Know .. is WHERE ARE YOU NOW !
And If We Suppose That Your parameters will not change until you consider to do this
(
Actually Thats Happend By surfing the internal array until reach the parameter Place
And Then Change It
And
The Most Important Thing To Know Here..Is What Is The value stored Before Change
(
But Why?
Because Humans Can Only Change Their Parameters By Increasing/Decreasing Its values
(
You Should Know That Humans Born (you don't have to know how or why) with initial value of ZERO
For Every Place in their internal array
)
)
)
The only way to know where are you (In the
Internal Array
)
and what Is the Value there IS to follow you from Born
to the point you are in now (you know humans lives on Average 00963113324820 ms on their planet Earth (The Average Brain Life)
and it's a little bit hard to follow them from the millisecond Zero To The millisecond 00963113324819 )...
Let's Talk A little About Humans Lifes
It's Not So Complicated,As They
Always move on
,(actually they can't stop the time until now :D Or even Go Back)..
they have an Internal Stack To Save A Check Points In their LIFE
..
These
Check Points
are the moments they call (Taking Decisions)
These Points Make two Branches In Humans Lifes (One Branch is to go on and
complete their life,executing every thing they supposed to do until reach the
Memory
Time,
Thats Also Make Two Branches one Is to Skip Memory Time And Go On
And The Other is (the Only Time They Go Back) they
pop the last check point
in their internal stack and go back to it,repeating every thing they've done from that moment)
(Second Branch IS That They DO NOTHING UNTIL they reach the memory time(discussed before)
and as they have No Memories They Skip The Memory time(never go back) and go on forward)
To Simulate Humans Life We Can write Mosty's Code.
What is Mosty's code?
Denote The Only 11 Actions Humans Do As Follow:
BORN
denotes Born ...(where human starts his life with empty stack and zero_value Places in intenral array of parameters)
DIE
denotes Die ...(where human End his life and rise/fall to paradise/Hell respectively ...
(actually it's a temporary pleasure/pain until the Judge Day Which We Will Not Discuss Here
(Which after it comes the endless pleasure/pain depends of what he done during his Short Life))
ENTER
denotes Enter His Internal Array
(Note: Humans Never Die When They Are in Their Internal Array (until they goes out)
Except in One situation will be Discussed later.)
EXIT
denotes Exit His Internal Array
(Note : ignore any actions out of The Internal Array)
(Note : when We Enter The Intenal array for the first time,So we are in place zero
Else we stay in the last place we were in)
DEEP
denotes moving Deeper In Mind (internal array)
(Note: if we were in the Deepest Place In mind then,we went deeper,we reach the zero place(as a modular Mind))
FLOAT
denotes moving Up Through the Mind (internal Array)
(Note: if we were in Place Zero,Then We Floated Up We reach The Deepest place in mind)
INCREASE
denotes increase the value stored in place(that we are in now) by one.
DECREASE
denotes decrease the Value Stored in place(that we are in now) by one
CHECKPOINT
denotes moments of(Take A Decision) (described before)
MEMORY
denoted Memory time when you human decide to go back or continue your life.
(Note: humans take a decision of executing their LifeCode included
After The CHECKPOINT AND before its associated MEMORY
IF and Only IF The Value He had in the last visited place in his mind was not ZERO
Else he will skip his LifeCode Included in that partition until he skips the associated Memory)
There is another 2 Actions(about interacting each other)We Will Not Discuss here.
Following One Human At Time You Are Going To Write A Program which Print
the values Of all Visited Places In His Mind (ONLY VISITED(ONLY))
using this form
PlaceNumber --> ItsValue
When to print ?
As you know values changes over his life ... so we will Define The Action '
*****
'
Which Denotes To The Moment Of '
Self Evaluation
'
The Input Is a part of One Human Life
But You Can Suppose these things :
1-The Human already Born , and he is old enough to enter his MIND .
2-he has already entered his mind(internal array).
3-He Has an initial values in his mind (you will get them in input).
4-he has initial place (also you will get it).
5-The Human Will Not Exit His Internal Array During The Analyziz.
6-The LifeCode (in this version)Contains only The Following Actions:
[DEEP,FLOAT,INCREASE,DECREASE,CHECKPOINT,MEMORY,*****]
7-*****.
Input Form:
First Line gives M P A S (separated by spaces)
M
: The Number Of
already visited places
(so you will get their values in the second line)...
[0<M<50]
.
P
: The
Last Place
this Human Were In his mind...
[0<=P<M]
.
A
: The
Number Of Actions
You Will Analyze...
[0<A<1000]
.
S
: The
Number Of 'Self Evaluation'
action will appeare ...
[0<=S<100]
.
[Note : for every 'Self Evaluation' action
you should print the value of all visited places
(as discussed later)]
Second Line Initiate The Values Of The First M value
(from 0 to M-1) of internal array.
Then Comes The
A
action Of this Human,7 in each line except the last one contain less.
The
Values
V[0] V[1] ... V[M-1] are
32 bit integers
(so that 0-1=-1 and 2147483647+1=-2147483648)
[note that A includes S].
Outputform:
for Every 'Self Evaluation' action you should print the values in places of internal array
using this form
PlaceNumber --> ItsValue
You Should
Print a jasmine flower before PlaceNumber
when PlaceNumber == The Last Place we've visited .
[what the hell is jasmine flower ? '*' ]
[note the spaces before and after the arrow]
[Note: You can
suppose that Humans Never Float in Mind When they are in place zero
or So that WILL KILL HIM (the only way to die during a mind trip)]
EXAMPLES:
Example1(Easy):
Input:
1 0 7 1
5
DEEP CHECKPOINT MEMORY FLOAT INCREASE DECREASE *****
Output:
*0 --> 5
1 --> 0
[the only place we've changed is 0 but we visit 1 also]
[note that we haven't enter the check point]
[note the Jasmin Flower]
Example2(medium):
Input:
5 2 15 4
0 1 2 3 4
INCREASE INCREASE CHECKPOINT DECREASE DEEP ***** INCREASE
INCREASE FLOAT MEMORY ***** DEEP ***** DECREASE
*****
Output:
0 --> 0
1 --> 1
2 --> 3
*3 --> 3
4 --> 4
0 --> 0
1 --> 1
2 --> 2
*3 --> 5
4 --> 4
0 --> 0
1 --> 1
2 --> 1
*3 --> 7
4 --> 4
0 --> 0
1 --> 1
2 --> 0
*3 --> 9
4 --> 4
0 --> 0
1 --> 1
*2 --> 0
3 --> 11
4 --> 4
0 --> 0
1 --> 1
2 --> 0
*3 --> 11
4 --> 4
0 --> 0
1 --> 1
2 --> 0
*3 --> 10
4 --> 4
Exmple3(HARD):
input:
1 0 6 0
1
CHECKPOINT DEEP FLOAT INCREASE DECREASE MEMORY
output:
AUTISM
[the last example not exists in this version :p
(actually I couldn't prevent myself from delete it as an example (btw it's true))]
Example3(HARD)
[real one]
:
Input:
1 0 82 11
0
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
INCREASE INCREASE CHECKPOINT DECREASE DEEP INCREASE INCREASE
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE DEEP
DEEP DEEP INCREASE INCREASE INCREASE INCREASE INCREASE
FLOAT FLOAT FLOAT FLOAT MEMORY DEEP CHECKPOINT
DECREASE DEEP INCREASE DEEP INCREASE FLOAT FLOAT
MEMORY DEEP DECREASE ***** DEEP DECREASE DECREASE
DECREASE ***** ***** FLOAT INCREASE INCREASE INCREASE
INCREASE ***** DEEP DEEP ***** FLOAT FLOAT
INCREASE INCREASE INCREASE INCREASE ***** DEEP DEEP
***** FLOAT DECREASE DECREASE ***** FLOAT *****
DEEP INCREASE ***** INCREASE *****
Output:
0 --> 0
1 --> 0
*2 --> 71
3 --> 72
4 --> 45
0 --> 0
1 --> 0
2 --> 71
*3 --> 69
4 --> 45
0 --> 0
1 --> 0
2 --> 71
*3 --> 69
4 --> 45
0 --> 0
1 --> 0
*2 --> 75
3 --> 69
4 --> 45
0 --> 0
1 --> 0
2 --> 75
3 --> 69
*4 --> 45
0 --> 0
1 --> 0
*2 --> 79
3 --> 69
4 --> 45
0 --> 0
1 --> 0
2 --> 79
3 --> 69
*4 --> 45
0 --> 0
1 --> 0
2 --> 79
*3 --> 67
4 --> 45
0 --> 0
1 --> 0
*2 --> 79
3 --> 67
4 --> 45
0 --> 0
1 --> 0
2 --> 79
*3 --> 68
4 --> 45
0 --> 0
1 --> 0
2 --> 79
*3 --> 69
4 --> 45
[if you noticed that S don't give the actual value of 'Self Evaluation'
you don't have to print more than 100 of it]
[as This human is not full trained in mind trips he will not go deeper than 10000 place
also he can't make a nested CHECKPOINTES of a depth more than 100]
last Example :
input:
10 9 180 1
0 0 0 0 0 0 0 0 0 13986
CHECKPOINT CHECKPOINT CHECKPOINT DECREASE DEEP INCREASE FLOAT
CHECKPOINT DECREASE DEEP INCREASE FLOAT CHECKPOINT DECREASE
DEEP INCREASE FLOAT CHECKPOINT DECREASE DEEP INCREASE
FLOAT CHECKPOINT DECREASE DEEP INCREASE FLOAT CHECKPOINT
DECREASE DEEP INCREASE FLOAT CHECKPOINT DECREASE DEEP
INCREASE FLOAT CHECKPOINT DECREASE DEEP INCREASE FLOAT
CHECKPOINT DECREASE DEEP INCREASE FLOAT CHECKPOINT DECREASE
DEEP INCREASE FLOAT FLOAT INCREASE DEEP DEEP
CHECKPOINT DECREASE MEMORY FLOAT CHECKPOINT DECREASE DEEP
DEEP INCREASE FLOAT FLOAT MEMORY MEMORY MEMORY
MEMORY MEMORY MEMORY MEMORY MEMORY MEMORY MEMORY
MEMORY DEEP DEEP CHECKPOINT DECREASE FLOAT FLOAT
INCREASE DEEP DEEP MEMORY FLOAT FLOAT MEMORY
FLOAT CHECKPOINT DECREASE DEEP DEEP DEEP INCREASE
FLOAT FLOAT FLOAT MEMORY DEEP DEEP CHECKPOINT
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE CHECKPOINT
DECREASE FLOAT FLOAT INCREASE DEEP DEEP MEMORY
MEMORY DEEP CHECKPOINT DECREASE FLOAT INCREASE DEEP
MEMORY FLOAT MEMORY FLOAT FLOAT CHECKPOINT *****
CHECKPOINT DECREASE MEMORY FLOAT MEMORY
Output:
0 --> 0
1 --> 0
2 --> 0
3 --> 0
4 --> 0
5 --> 0
6 --> 0
7 --> 0
8 --> 54
9 --> 56
10 --> 57
11 --> 51
*12 --> 49
13 --> 0
14 --> 0
15 --> 0
0 --> 0
1 --> 0
2 --> 0
3 --> 0
4 --> 0
5 --> 0
6 --> 0
7 --> 0
8 --> 54
9 --> 56
10 --> 57
*11 --> 51
12 --> 0
13 --> 0
14 --> 0
15 --> 0
0 --> 0
1 --> 0
2 --> 0
3 --> 0
4 --> 0
5 --> 0
6 --> 0
7 --> 0
8 --> 54
9 --> 56
*10 --> 57
11 --> 0
12 --> 0
13 --> 0
14 --> 0
15 --> 0
0 --> 0
1 --> 0
2 --> 0
3 --> 0
4 --> 0
5 --> 0
6 --> 0
7 --> 0
8 --> 54
*9 --> 56
10 --> 0
11 --> 0
12 --> 0
13 --> 0
14 --> 0
15 --> 0
0 --> 0
1 --> 0
2 --> 0
3 --> 0
4 --> 0
5 --> 0
6 --> 0
7 --> 0
*8 --> 54
9 --> 0
10 --> 0
11 --> 0
12 --> 0
13 --> 0
14 --> 0
15 --> 0
________________________________________________________________________
Thanks For
Mitch Schwartz
for his last problems
where the idea has come from. | 33,281 |
Partition function (EASY) (PARCARD1)
You need to output the number of distinct ways of representing
n
as a sum of natural numbers (with order irrelevant) for all integer
n
from 0 to 10000 inclusive.
First numbers of output must be:
1 1 2 3 5 7 11 15 22 30 42 56 77 | 33,282 |
Partition function (HARD) (PARCARD2)
You need to output the number of distinct ways of representing
n
as a sum of natural numbers (with order irrelevant) for given integer n.
Input
n, 0 ≤ n ≤ 10
8
Example
Input:
2013
Output:
6805659785780163657391920602286596663406217911 | 33,283 |
Large Knapsack (LKS)
The
knapsack problem
or
rucksack problem
is a problem in
combinatorial optimization
: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size
knapsack
and must fill it with the most valuable items.
Just implement 0/1 Knapsack.
Input
First line contains two integers K and N, where K in the maximum knapsack size and N is the number of items. N lines follow where i
th
line describes i
th
item in the form v
i
and w
i
where v
i
is the value and w
i
is the weight of i
th
item.
Output
Output a single number - maximum value of knapsack. (All operations and the answer are guaranteed to fit in signed 32-bit integer.)
Time limit changed to 2s on 02.07.11.
Example
Input:
10 3
7 3
8 8
4 6
Output:
11
Constraints
K <= 2000000
N <= 500
V
i
<= 10^7
W
i
<= 10^7 | 33,284 |
III Powers (THRPWRS)
Consider the set of all non-negative integer powers of 3.
S
= { 1, 3, 9, 27, 81, ... }
Consider the sequence of all subsets of
S
ordered by the value of the sum of their elements. The question is simple: find the set at the
n
-th position in the sequence and print it in increasing order of its elements.
Each line of input contains a number
n
, which is a positive integer with no more than 19 digits. The last line of input contains 0 and it should not be processed.
For each line of input, output a single line displaying the
n
-th set as described above, in the format used in the sample output.
Example
Input:
1
7
14
783
1125900981634049
0
Output:
{ }
{ 3, 9 }
{ 1, 9, 27 }
{ 3, 9, 27, 6561, 19683 }
{ 59049, 3486784401, 205891132094649, 717897987691852588770249 } | 33,285 |
FRIEND CIRCLE (FRNDCIRC)
Lucy has made too many friends but she does not know how many friends are in her circle. Assume that every relation is mutual. If Lucy is Patty's friend, then Patty is also Lucy's friend. Your task is to help Lucy in keeping track of each person's circle size.
Input Specification
The first line of input contains one integer T (
T<=10
) specifying the number of test cases to follow. Each test case begins with a line containing an integer N
(N<=100000)
, the number of new relations. Each of the following
N
lines contains couple of strings denoting the names of two people who have just formed relation, separated by a space. Names will have no more than
20
characters.
Output Specification
Print a line containing one integer, the number of people in the combined circle of two people who have just become friends.
Input
1
4
Lucy Patty
Patty Alice
Alice Mira
Tiffany Jayden
Output
2
2
3
4
2 | 33,286 |
A plus B (ICKAPLSB)
You only need to print the sum of two digits. Note that the only available language is ICK.
Input
Two digits
a
and
b
from {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, separated by a space.
Output
a+b
Example
Input:
5 5
Output:
10 | 33,287 |
Defend The Rohan (ROHAAN)
Kingdom of Rohan is under attack! There are N vital army stations. King will decide what army should be guarding what station, to get the best strategic advantage against Sauron attacks. All armies are already in some stations, but not necessarily the stations required by the king. As a result armies will have to be moved. Distances between any pair of stations are known. They are not necessarily symmetrical, because road from station A to B could be different than road from B to A. When a army moves, it doesn't have to take a direct road and instead can choose to cross other stations, if that results in a shorter path.
Given the distances between stations and king's relocation orders, find the minimum total travel distance for all the armies.
Input
First line contains an integer
T
, number of test cases. Then the description of
T
test cases follow. Each test case starts with an integer
N
, which is the total number of army stations. Next
N
lines have
N
integers each, description of distances.
b
'th integer on line
a
is the distance from station
a
to station
b
. Description of kings orders follows. In a first line, a single integer
R
, number of orders. Next
R
lines will contain two integers
s
and
d
each, describing an order to move an army from station
s
to
d
.
Constrains:
1 <= T <= 50
1 <= N, R <= 50
1 <= distance <= 10^6
1 <= s, d <= N
Output
Print a single line for each test case. A string "Case #t: " without quotes, where
t
is the number of test case, starting from 1. Following the string, you must print the total distance armies must travel during relocation.
0 <= total distance <= 10^7
Example
Input:
1
3
0 1 1
1 0 1
1 9 0
2
2 1
3 2
Output:
Case #1: 3 | 33,288 |
Peter Quest (VPL2_BC)
Is Peter’s birthday! And his friends are preparing a big party, however, Peter is obsessed with a variation of the famous game Minesweeper, moreover, Peter hates losing, so if any of you or your friends can beat him in the game, he will get angry and will attend the party that everyone is organizing for him.
This new mode of Minesweeper consists in building the gameboard given the mines, so, if the matrix has size of (2×2) and there is a mine in the position (0, 0) of the matrix, the resultant gameboard will be *1 11 Your task is to beat Peter and celebrate his birthday before its too late! Please have in consideration that:
The cell (i, j) where there is a mine will be denoted as ’*’.
The cell (i, j) where there is no mine will be denoted as ’-’.
The cell (i, j) where there is N mines adjacent to it, will be denoted as a number from 1 to 8 (depending on the number of adjacencies.)
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
For each test case, you will have a line with three numbers N, M, K, denoting, respectively, the size of the matrix, formed by N columns and M rows, and K mines. Then, K lines will follow, each containing two numbers Ki and Kj denoting the position where the mine is in the board.
Output
For each test case you should print the string "Scenario #i:" where i represents the test case you are analyzing (starting from 1), then, in the next line, you shall print the gameboard as specified.
Example
Input:
3
3 2 2
0 0
1 1
3 3 3
0 0
1 1
2 2
8 8 10
0 1
5 0
2 5
4 5
2 6
5 6
6 6
5 7
6 7
7 7
Output:
Scenario #1:
*2
2*
11
Scenario #2:
*21
2*2
12*
Scenario #3:
1*1-----
111-1221
----1**1
----2331
11--1*32
*1--13**
11---2**
-----13*
Constraints
Subtask 1 (10%)
1 ≤ T ≤ 10
1 ≤ N, M ≤ 8
1 ≤ K ≤ min(8, N×M)
Subtask 2 (20%)
1 ≤ T ≤ 10
1 ≤ N, M ≤ 128
1 ≤ K ≤ min(128, N×M)
Subtask 3 (30%)
1 ≤ T ≤ 10
1 ≤ N, M ≤ 1024
1 ≤ K ≤ min(1024, N×M)
Subtask 4 (40%)
1 ≤ T ≤ 10
1 ≤ N, M ≤ 6144
1 ≤ K ≤ min(100000, N×M) | 33,289 |
Annoying Coins Quest (VPL2_BE)
Little Tita has always been annoyed by coins, she’s so annoyed that has devised a formula to assign an annoyment level to each transaction. The formula is quite simple, each coin c has a transfer annoyment value (Tc) and a keep annoyment level (Kc), then, each transaction has a total annoyment level (A) defined as the sum of the transfer annoyment (AT) and the kept annoyment (AK). Where:
Given the list of coins that exist, the cost of a transaction and the list coins Tita has; find the minimum total annoyment level that Tita can guarantee for the transaction assuming the seller has an infinite amount of coins of each type and is not at all thinking about Tita’s annoyment level formula.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Each test case will start with two integer N, the number of coin types that exist, and C, the cost of the transaction. The next N lines describe each coin type by with three integers Vi, Ti and Ki which represent the value, transfer annoyment and keep annoyment, respectively. Finally, a line with N integers Ai represent the amount of coins Tita has of each type, in the same order as the coins description.
Output
For each input case you must print a single line with the string Scenario #i: x, where i is the number of the test case (starting at 1), and x is the minimum annoyment level that Tita can guarantee for the transaction or −1 if the transaction cannot be made.
Input:
3
3 11
2 1 10
10 20 20
3 1 1
2 1 0
4 11
2 1 10
10 20 20
3 1 1
1 10 1
2 1 0 0
2 3
4 1 1
3 1 1
1 0
Output:
Scenario #1: 24
Scenario #2: 42
Scenario #3: -1 | 33,290 |
Hunter x Hunter (HXH)
Gon and Killua are two very talented hunters, and they are also very skilled fighters, however it is well known that Killua is faster and smarter than Gon, and Gon is stronger and is way more decided than Killua. That makes them almost the perfect team (they just need more time to become the most skilled hunters that ever lived) and they are so good as a team that they decided to fight and defeat many enemies (as much as they can) so they made a plan, as the enemies are in a N x N grid Gon decided to start at position 0,0 of this grid and Killua at position n-1,n-1. To maximize the number of defeated enemies Gon moves only to the Right and Down, and Killua to the Left and Up, they count how many enemies they defeated and stop when both of them are in the same cell and they give each other a high five. So if they complete the ride without doing this they will be mad, so that will not be a solution.
However Killua wants this to be perfect, so he is tracing a new plan, but he does not know the best ride, as you are an amazing programmer he asked you for your help and you need to give him the maximum amount of enemies they can defeat together and then give each other a high five, only with this information the super brain of Killua will figure out the rest.
Remember, the ride will not finish if they do not give each other that high five.
The grid has this properties:
‘#’ is an obstacle that neither Gon nor Killua can pass through.
‘.’ is a walkable area.
‘*’ is an enemy.
Also they move at the same time, if any of them cannot move, it will not be a valid move. They never stand still.
Input
The input consist on several test cases represented by T each of them start with an 2 <= N <= 500 the size of the grid and the grid itself.
Output
Just show the maximum number of enemies that both can defeat, and then give each other a high five. If this cannot be done print -1.
Sample
Input:
1
5
..*..
.*..*
#...*
..*..
.....
Output:
3
They could defeat all 5 if they weren’t going to give each other a high five, but as they do and they never stand still, they will defeat only 3 and then give a high five, Killua defeats 2 and Gon 1. | 33,291 |
Hello Intercal! (ICKHELLO)
All you need to do Is to print "
HELLO-INTERCAL
", of course, using INTERCAL.
Input
No input.
Output
HELLO-INTERCAL
Example
Input:
Output:
HELLO-INTERCAL | 33,292 |
World Record Lunch (WRLUNCH)
A group of people is trying to beat the world record for the largest number of people having lunch at the same time. In order achieve this goal, they are using the country's largest bridge and they have decided to arrange the tables following the shape of the letter 'S'.
The table layout can be described by 4 integers:
NH
,
NV
,
H
and
V
. The two first integers,
NH
and
NV
, represent respectively the number or rows and number of columns in the layout. The last two integers represent respectively the number of tables in each row and column. For a given layout, the tables are numbered consecutively, starting with table #1 in the top-right corner. The following figure illustrates several possible layouts:
Thousands of groups of people are expected to come, and the organizers have to define where to seat everyone. Each group needs a certain number of tables and they do not share tables with other groups. Furthermore, a group wants their tables to be together and not split among rows and columns, that is, they want a set of consecutive tables either on the same row or on the same column. If this condition cannot be met, the group prefers to go away and have lunch at another place. The groups also enjoy having some privacy and prefer unoccupied adjacent tables, that is, no one at the table exactly before the first table of the group, and no one at the table exactly after the last table of the group. If this happens, we say that the group found a
private
place.
Whenever a group arrives, the organization must decide where to seat that group based solely on the table occupation at the moment, without taking into account further groups that may be coming. Since a group will always be seated on consecutive tables, the position of a group can be defined by the index of the first table of the group. So, when a group arrive, the organization wants the following:
If there is a suitable private place for the group, then choose the lowest possible index guaranteeing privacy;
If no privacy can be ensured, but there is space for the group, then choose the lowest possible index with space for the entire group;
If there is no space available on a single row or column where the group would fit, then the organizers must send the group away.
An example would be the following. Imagine a layout with
NH
=3,
NV
=2,
H
=5 and
V
=3 (the first layout give on the figure above). And now imagine that groups needing 5, 2, 3, 5, 4 and 2 tables arrive, in that order. This is what happens:
In the beginning all tables are empty
Group 1 needs 5 tables. It is put on index 1.
Group 2 needs 2 tables. It is put on index 7.
Group 3 needs 3 tables. It is put on index 11.
Group 4 needs 5 tables. No position is available.
Group 5 needs 4 tables. It is put on index 14 (with no privacy).
Group 6 needs 2 tables. It is put on index 9 (with no privacy).
Can you help the organizers on this task?
The Problem
Given a table layout (number of rows, columns and number of tables per row and column) and the description of groups arriving (specifying number of tables needed per group), your task is to calculate where each group should be seated following the rules described above.
Input
The first line contains 5 integers
NH NV H V N
, separated by single spaces.
NH
and
NV
indicate respectively the number of rows and columns of the table layout.
H
and
V
indicate respectively the number of tables per row and column.
N
indicates the number of groups arriving.
Then come
N
lines, each one indicating
G
i
, the number of tables the
i
-th group needs. These lines come in order of arrival of the groups.
Output
The output should have exactly
N
lines, each one indicating where the respective group should seat. If there is a suitable position, the line should contain an integer indicating the index of the first table of the group. If no position is available, the line should contain the string
"no"
, without the quotes.
Restrictions
The following limits are guaranteed for all the test cases that will be used for evaluating your program:
1 ≤ NH ≤ 10 000
Number of rows
NH-1 ≤ NV ≤ NH
Number of columns
3 ≤ H,V ≤ 1 000
Number of tables in each row/column
1 ≤ N ≤ 50 000
Number of groups
1 ≤ G
i
≤ 1 000
Number of tables each group needs
Example Input 1
3 2 5 3 6
5
2
3
5
4
2
Example Output 1
1
7
11
no
14
9
Input Explanation 1
It is the example given before in the problem statement.
Example Input 2
2 2 3 3 3
3
3
1
Example Output 2
1
5
9
Input Explanation 2
In the end the tables would look like this:
A few notes:
This is the first problem I add to SPOJ, hope you like it :)
The time limit is at least 6x the runtime of my C++ solution with no low-level optimizations or fast input/output. I have a Java solution passing within these time limits.
I'm not proficient enough in languages like Python to ensure the time limit is ok for those languages. I can increase the limits if needed. | 33,293 |
Running Median (RMID)
You will be given some integers in non decreasing order and each time the median is queried you have to report and remove it. Take the smaller element as median in case of even elements.
Input
The input contains many test cases. Read until End Of File.
Each test case contains n (n ≤ 100000) positive integers in non-decreasing order, along with m queries indicated by -1, all on separate lines. (See the example.)
For a query, print the current median on a single line and remove it from the list.
Each test case ends with 0 on a single line, and two test cases will be separated by an empty line. All integers are guaranteed to fit in a signed 32-bit container. A query can only occur if the list is non-empty.
Output
For each test case output m lines containing the answers to the corresponding queries. Print an empty line after each test case.
Example
Input:
1
2
3
4
-1
-1
5
6
7
-1
0
2
3
-1
0
Output:
2
3
5
2 | 33,294 |
Cut The Rope (BFGCD)
Budi is a rope seller, He initially has two ropes to sell with length
a
and
b
where
a
and
b
is positive integer less than 10
100
. One day he meet with strange rich customer, the customer want to buy all rope with equal length only. Budi has an idea to sell all his rope to that customer: cut the rope until all his rope become equal length. Because Budi want maximum profit, he need to minimize the "cut" operation. But the customer doesn't like waiting, so Budi must calculate and do "cut" operation quickly.
The customer can wait 60 seconds only, Budi can cut the rope in exactly 10 seconds, so Budi have 50 seconds to calculate number of "cut" operation needed.
Help Budi to calculate number of "cut" operation and length of each rope after cutting process done. But unfortunately your modern calculator isn't working, so the only way to do is using
brainf**k
calculator, with 8 valid commands only. Will you help Budi?
Input
First line of input there is an integer
T
≤ 1000 denoting number of test case.
Next
T
lines there're two positive integer
a
and
b
denoting length of rope that Budi has initially. Separated by a space (ASCII:32).
Each line is terminated with newline character (ASCII:10).
Output
For each case, output two number: first number is minimum number of cut operation, and second number is length of each rope after cutting process done.
Example
Input:
4
1 42
42 1
42 42
12345 67890
Output:
41 1
41 1
0 42
5347 15
Other Info
Input: generated 99.9% random with average digit is about 74.8 digits
Output: Average digit for "cut" operation is about 34.7 digits, and length of rope after cutting process done is about 49.0 digits.
This problem is using custom judge, so you can see the detail after you get AC/WA.
Judge output format is like this: ("
Code Length (Valid Command only)
")"
Cell Used
"("
BF Command executed
").
Click here to see my submission result for this problem.
Judge output for my BF code is: (11820)1157(6571171311) meaning that my Valid BF commands = 11820 commands and My code using 1157 BF cell and 6571171311 commands executed.
You can click (AC/WA) status for more detail.
My code running time is 6.95s and using 1.9M of memory.
Time limit is ~7× my BF program speed.
See also:
Another problem added by Tjandra Satria Gunawan | 33,295 |
Factorial (Again!) (FCTRL5)
Have you solved
FCTRL
problem?
In this problem you need to do the same task (given positive integer
n
< 10
100
you need to count number of zeroes at the end of the decimal number of
n!
), seems easy(?) but this time only Brainf**k language allowed.
Input
First line of input there is an integer
T
≤ 1000 denoting number of test case.
Next
T
lines containing an integer
n
.
Each line is terminated with newline character (ASCII:10)
Output
For each test case, output number of zeroes at the end of the decimal form of number
n!
Example
Input:
6
3
60
100
1024
23456
8735373
Output:
0
14
24
253
5861
2183837
Other Info
Input: 100% random log-uniform.
This problem is using custom judge, so you can see the detail after you get AC/WA.
Judge output format is like this: ("
Code Length (Valid Command only)
")"
Cell Used
"("
BF Command executed
").
Click here to see my submission result for this problem.
Judge output for my BF code is: (1340)501(392776170) meaning that my Valid BF commands = 1340 commands and My code using 501 BF cell and 392776170 commands executed.
You can click (AC/WA) status for more detail.
My code running time is 0.59s and using 1.6MB of memory.
Time limit is ~16× my BF program speed.
See also:
Another problem added by Tjandra Satria Gunawan | 33,296 |
Transform the Expression (Again!) (BFONP)
Have you solved
ONP
problem? Especially using
brainf**k
? This problem will give you extra points if you can solve
ONP
using
brainf**k
. Note that this problem has larger constraints.
The task is: "Transform the algebraic expression with brackets into RPN form (Reverse Polish Notation). Two-argument operators: +, -, *, /, ^ (priority from the lowest to the highest), brackets ( ). Operands: only letters: a,b,...,z. Assume that there is only one RPN form (no expressions like a*b*c)."
Input
t [the number of expressions ≤ 1000]
expression
[length = See: "Other Info" part]
[other expressions]
Output
The
expressions
in RPN form, one per line.
Example
Input:
3
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))
Output:
abc*+
ab+zx+*
at+bac++cd+^*
Other Info
Input: I deliberately not tell the input length, constraints, distribution, etc. You can guess it from judge output for my BF program (BF Cell Used) ;-) And of course I generate it randomly (But I can't tell the distribution).
This problem is using a custom judge, so you can see the detail after you get AC/WA.
The judge output format is like this: ("
Code Length (Valid Command only)
")"
Cell Used
"("
BF Command executed
").
Click here to see my submission result for this problem.
I have two solutions for this problem:
1) ID 9658441 (optimized): Judge output for my BF code is: (471)4320(606116310) meaning that my Valid BF commands = 471 commands and My code using 4320 BF cell and 606116310 commands executed.
2) ID 9658572 (golfed): Judge output for my BF code is: (295)4320(888371635) meaning that my Valid BF commands = 295 commands and My code using 4320 BF cell and 888371635 commands executed.
You can click (AC/WA) status for more detail.
My code running time is 0.68s (optimized solution) and 1.47s (golfed solution) and both using 1.6M of memory.
The time limit is ~14× my BF program top speed.
See also:
Another problem added by Tjandra Satria Gunawan | 33,297 |
Counting Ids (UCV2013A)
Little Willy just took a compilers course and is trying to implement his own compiler. First he wants to build a table with all the possible ids that a program could have. He knows that his language supports up to N different characters and any id can be up to L characters long. For example, when N = 2 (lets say characters can be 0 or 1), and L = 3, he could have the following ids: {0, 1, 00, 01, 10, 11, 000, 001, 010, 011, 100, 101, 110, 111}.
You have to write a program that can help Willy find out the size of the table. Since the answer can be really big, you must print it modulo 1000000007 (10^9+7).
Input
The input contains several test cases. Each test case will consist of a single line containing two integers N and L. N is the number of characters that can be part of an id and L is maximum length supported by the language (1 <= N <= 65535, 1 <= L <= 10^5).
End of the input is indicated by a test case with N = 0, L = 0 that should not be processed.
Output
For each test case output a single line containing the number of possible ids modulo 10^9+7.
Example
Input:
2 3
128 32
0 0
Output:
14
792805767 | 33,298 |
Alice in Amsterdam, I mean Wonderland (UCV2013B)
This is a fact that not many people know, but Alice lived in Amsterdam. Yes, there you go. And as many kids of the time, she used to go for some medicinal mushrooms to the drug store (the pharmacies, the coffee shops didn't exist yet). Usually, between the regular mushrooms, a magical one could be found, producing as expected, deep and vivid hallucinations. During one of those hallucinations, Alice was transported to a "wonderland", where many weird things happened. One thing was particularly dazzling for her: even though everything looked pretty familiar, the distance between monuments of the city was sometimes negative!!! Although, zero distance between two different monuments means a direct path doesn't exist. A loop from a given monument right back to it can be of length zero (with means that it can be reached instantly like in real life) or negative, like for regular paths. Alice also thought that she saw some positive distances for loops, but we should treat those cases as zero distance.
Now, as a very smart girl as she is, she figured out a way to find the shortest path between any two monuments. Unfortunately, as expected, Alice forgot it when she got sober again. She was only able to remember that, in some cases, she could get stuck in a cycle path with negative distance. In such cases, there will always be a cheaper path to get to the same monument. This was one of the few things that had perfect sense for her: Your shortest path will be shorter if you take that cycle again and again, to infinity. Alice, has been trying to figure optimal distances all over again, but she can't. She doesn't want to trip again, she has been clean for longer than a year (good for her!!). Would you be so kind to help her?
Given a list of monuments in a city, and their relative distances, find the shortest paths between some pairs of monuments.
Input
Each case, starts with one line containing
N
, the number of monuments in the test case (1 ≤
N
≤ 100). Next N lines will each contain one string
K
and
N
integers
Kj
, separated by single spaces.
K
is a name of a monument and will consist of at most 20 alphanumeric characters. Each integer
Kj
(0 ≤
j
<
N
) in line
i
describes the distance from monument i to j (-2
30
≤
Kj
≤ 2
30
). Next line will contain a single integer
Q
(1 ≤
Q
≤
N
2
). It will be followed by Q lines, each with a pair of integers (
U
,
V
), indicating the start and destination monument for the path that is queried (0 ≤
U
,
U
<
N
).
End of the input is indicated by a test case with
N
= 0 and should not be processed.
Output
For each test case, print a line "Case #
tc
:" (without quotes), where tc is the case number, starting from 1. Next
Q
lines should describe query results. If the optimal distance can be infinitely small, print only "NEGATIVE CYCLE". In other cases, start the line with "
start_name
-
destination_name
" followed by the actual result. If the destination can't be reached, print "NOT REACHABLE", otherwise print the integer distance.
Example
Input:
2
Nieuwkerk -1 1
Oudekerk 1 0
4
0 0
0 1
1 1
1 0
3
Nieuwkerk 0 -5 0
Oudekerk 10 0 0
Pierteck -100 -100 0
9
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
0
Output:
Case #1:
NEGATIVE CYCLE
NEGATIVE CYCLE
NEGATIVE CYCLE
NEGATIVE CYCLE
Case #2:
Nieuwkerk-Nieuwkerk 0
Nieuwkerk-Oudekerk -5
Nieuwkerk-Pierteck NOT REACHABLE
Oudekerk-Nieuwkerk 10
Oudekerk-Oudekerk 0
Oudekerk-Pierteck NOT REACHABLE
Pierteck-Nieuwkerk -100
Pierteck-Oudekerk -105
Pierteck-Pierteck 0 | 33,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.