Google Code Jam Archive — Round 2 2011 problems

Overview

Round 2 started off with a flurry of submissions to problem A. After that, half of the contestants chose to work on B; others started on C. austrin was the lone dissenter, solving the tricky D at the 28-minute mark. He was the only person on the scoreboard with a correct D-large for a long time.

By the end of the first hour of competition, two-time champion acrush took the lead for the first time in Code Jam 2011, with correct solutions to problems A, B and C. Ahyangyi and mystic followed him soon after, with their own error-free solutions to those problems. At that point, it was a race to see whether austrin could finish the rest of the problems before anybody else figured out a solution to D -- a tricky graph theory problem.

At the 1h7m mark, acrush submitted a correct solution to D-large, decisively taking first place. Ten minutes later, mystic and meret followed with correct solutions of their own, taking second and third place, respectively. austrin ended up solving the four problems in the order (D, B, C, A) and earning fourth place.

Congratulations to all contestants who have won t-shirts, and good luck to the top 500 in Round 3!



Cast

Problem A. Airport Walkways Written by Bartholomew Furrow and Onufry Wojtaszczyk. Prepared by Tomek Czajka.

Problem B. Spinning Blade Written by Igor Naverniouk and Onufry Wojtaszczyk. Prepared by Onufry Wojtaszczyk.

Problem C. Expensive Dinner Written by Bartholomew Furrow. Prepared by Onufry Wojtaszczyk.

Problem D. A.I. War Written by Bartholomew Furrow. Prepared by Onufry Wojtaszczyk.

Contest analysis by Stephen Fulwider, Jonathan Calhoun, David Arthur and Tomek Czajka.

Solutions and other problem preparation by Jorge Bernadas Saragoza, Bartholomew Furrow, Tomek Czajka, Igor Naverniouk, Stephen Fulwider, Md. Arifuzzaman Arif, David Arthur, Stephen Thomas and Konstantin Azarov.

A. Airport Walkways

Problem

You're in an airport, standing at point 0. A corridor of length X leads to the gate, where your plane is about to leave. There are moving walkways in the corridor, each moving with some speed wi. When you walk or run on one of those, you move with speed (your speed + wi). The walkways do not change their position; they just make you move faster. The walkways do not overlap: at any given point of the corridor there is at most one walkway, but one walkway can begin at the point where another ends.

Your normal walking speed is S. You are worried that you might not catch your plane, though, so you can run a bit - you can run with speed R for at most t seconds in total. You do not have to run for t consecutive seconds: you can split these t seconds into any number of intervals, or even not use some part of them.

How long does it take you to get to the gate, assuming you choose when to walk and when to run in order to reach it as soon as possible?

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 containing five integers: X (the length of the corridor, in meters), S (your walking speed, in meters per second), R (your running speed, in meters per second), t (the maximum time you can run, in seconds) and N (the number of walkways).

Each of the next N lines contains three integers: Bi, Ei and wi - the beginning and end of the walkway (in meters from your starting point) and the speed of the walkway (in meters per second).

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 time (in seconds) you need to reach point X if you walk and run optimally. Answers with relative or absolute error of at most 10-6 will be accepted.

Limits

1 ≤ T ≤ 40.
1 ≤ S < R ≤ 100.
1 ≤ wi ≤ 100.
0 ≤ Bi < EiX.
EiBi+1.
Memory limit: 1GB.

Small dataset (Test set 1 - Visible)

1 ≤ t ≤ 100.
1 ≤ X ≤ 100.
1 ≤ N ≤ 20.
Time limit: 30 seconds.

Large dataset (Test set 2 - Hidden)

1 ≤ t ≤ 106.
1 ≤ X ≤ 106.
1 ≤ N ≤ 1000.
Time limit: 60 seconds.

Sample

Sample Input
content_copy Copied!
3
10 1 4 1 2
4 6 1
6 9 2
12 1 2 4 1
6 12 1
20 1 3 20 5
0 4 5
4 8 4
8 12 3
12 16 2
16 20 1
Sample Output
content_copy Copied!
Case #1: 4.000000
Case #2: 5.500000
Case #3: 3.538095238

The best solution in the first case is to start running immediately and run for one second.

B. Spinning Blade

Problem

Being bored with the traps in your secret hideout design, you decided to go for something classical, but always enjoyable - the spinning blade. You ordered a really heavy metal sheet out of which you will cut the blade; a uniform square C-by-R grid will be painted on the sheet. You have determined the best shape for the blade -- you will first cut a large square consisting of K-by-K grid cells, where K ≥ 3. Then, you will cut out the four 1-by-1 corner cells out of the square to end up with a blade. After determining all this, you started waiting for the sheet to arrive.

When the sheet arrived, you were shocked to find out that the sheet had imperfections in it! You expected each cell to have mass D, but it turned out that the mass can vary a bit because of differences in thickness. This is bad because you want to insert a shaft exactly in the center of the blade and spin it very fast, so the center of mass of the blade must be exactly in its center as well. The definition of the center of mass of a flat body can be found below.

Given the grid and the mass of each cell, what is the largest possible size of the blade you can make so that the center of mass is exactly in its center?

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each one starts with a line containing 3 integers: R, C and D — the dimensions of the grid and the mass you expected each cell to have. The next R lines each contain C digits wij each, giving the differences between the actual and the expected mass of the grid cells. Each cell has a uniform density, but could have an integer mass between D + 0 and D + 9, inclusive.

Output

For each test case, output one line containing "Case #x: K", where x is the case number (starting from 1) and K is the largest possible size of the blade you can cut out. If no acceptable blade of size at least 3 can be found, print "IMPOSSIBLE" instead.

Limits

1 ≤ T ≤ 20.
0 ≤ wij ≤ 9.
The size of the input file will not exceed 625KB.
Memory limit: 1GB.

Small dataset (Test set 1 - Visible)

3 ≤ R ≤ 10.
3 ≤ C ≤ 10.
1 ≤ D ≤ 100.
Time limit: 30 seconds.

Large dataset (Test set 2 - Hidden)

3 ≤ R ≤ 500.
3 ≤ C ≤ 500.
1 ≤ D ≤ 106.
Time limit: 60 seconds.

Sample

Sample Input
content_copy Copied!
2
6 7 2
1111111
1122271
1211521
1329131
1242121
1122211
3 3 7
123
234
345
Sample Output
content_copy Copied!
Case #1: 5
Case #2: IMPOSSIBLE

Note

The center of mass of a 2D object is formally defined as a point c. If you compute the sum of (p - c) * mass(p) for all points p in the object, you must get 0. Here, p, c and 0 are two-dimensional vectors. This definition also works if you treat each grid cell as a "point", with all of its mass at its center.

In real life, you could place your finger under a flat object's center of mass, and balance that object on your finger. It would not fall.

To illustrate with an example, the only blade that is possible to cut out in the second sample test case, the 3x3 blade created by cutting away the corners, has its center of mass at the point (1.54, 1.46), where we assume the bottom-left corner of the sheet has coordinates (0, 0), and the coordinates grow right and up, respectively. This is verified by checking the following equality: (-1.04, 0.04) * 9 + (-0.04, 1.04) * 9 + (-0.04, 0.04) * 10 + (-0.04, -0.96) * 11 + (0.96, 0.04) * 11 = (0, 0).

C. Expensive Dinner

Problem

Your friends are all going to a restaurant for dinner tonight. They're all very good at math, but they're all very strange: your ath friend (starting from 1) will be unhappy unless the total cost of the meal is a positive integer, and is divisible by a.

Your friends enter the restaurant one at a time. As soon as someone enters the restaurant, if that person is unhappy then the group will call a waiter immediately.

As long as there is at least one unhappy person in the restaurant, one of those unhappy people will buy the lowest-cost item that will make him or her happy. This will continue until nobody in the restaurant is unhappy, and then the waiter will leave. Fortunately, the restaurant sells food at every integer price. See the explanation of the first test case for an example.

Your friends could choose to enter the restaurant in any order. After the waiter has been called, if there is more than one unhappy person in the restaurant, any one of those unhappy people could choose to buy something first. The way in which all of those choices are made could have an effect on how many times the group calls a waiter.

As the owner of the restaurant, you employ some very tired waiters. You want to calculate the spread of your friends: the difference between the maximum number of times they might call a waiter and the minimum number of times they might call a waiter.

Input

The first line of the input gives the number of test cases, T. T test cases follow, each on its own line. Each test case will contain one integer N, the number of friends you have.

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 spread for that test case.

Limits

Memory limit: 1GB.

Small dataset (Test set 1 - Visible)

1 ≤ T ≤ 100.
1 ≤ N ≤ 1000.
Time limit: 30 seconds.

Large dataset (Test set 2 - Hidden)

1 ≤ T ≤ 1000.
1 ≤ N ≤ 1012.
Time limit: 60 seconds.

Sample

Sample Input
content_copy Copied!
4
1
3
6
16
Sample Output
content_copy Copied!
Case #1: 0
Case #2: 1
Case #3: 2
Case #4: 5

Explanation

In Case #2, suppose your friends arrive in the order [1, 2, 3]. Then #1 arrives; is unhappy; calls a waiter; and buys something costing 1. Now nobody is unhappy. #2 arrives next; is unhappy; calls a waiter; and buys something costing 1 (for a total of 2). Now nobody is unhappy. #3 arrives next; is unhappy; calls a waiter; and buys something costing 1 (for a total of 3). Now #2 is unhappy, and buys something costing 1 (for a total of 4). Now #3 is unhappy, and buys something costing 2 (for a total of 6). Finally nobody is unhappy, and a waiter was called three times.

Suppose instead that your friends arrived in the order [3, 1, 2]. Then #3 arrives; is unhappy; calls a waiter; and buys something costing 3. Now nobody is unhappy. #1 arrives next; nobody is unhappy. #2 arrives next; is unhappy; calls a waiter; and buys something costing 1 (for a total of 4). Now #3 is unhappy, and buys something costing 2 (for a total of 6). Now nobody is unhappy, and a waiter was called two times. The spread is 1.

D. A.I. War

Introduction

A.I. War is a real-time strategy game developed by Arcen Games. This problem was inspired by the game, but does not assume you have played it.

Problem

You're facing an artificial intelligence in a deadly war for the future of the galaxy. In order to defeat the A.I., you will need to threaten its home planet. Some planets are connected to each other by wormholes; any planet may be connected to any number of other planets using the wormholes.

You begin by owning only your home planet. Each turn, you may conquer any planet you threaten. You threaten a planet if you don't own it, and it is connected by a wormhole to any of the planets you own. Once you have conquered a planet, you own it. As soon as you threaten the A.I.'s home planet, you may not conquer any more planets.

While attending the most important day in tactical school, you discovered two things about the A.I.:

  • For each planet you conquer, the A.I. will become more powerful, because it will see you as a threat and produce more ships to defend itself.
  • The A.I. will defend every planet you're currently threatening.
You have combined those two facts to create a strategy:
  1. You will conquer planets until you threaten the A.I.'s home base.
  2. If there are multiple ways of completing step 1, do it while conquering the smallest possible number of planets.
  3. If there are multiple ways of completing step 2, do it so that at the end you will threaten the largest possible number of planets.

Given the planets and the wormholes, how many planets will you conquer and threaten on your way to the A.I.'s home base if you follow the strategy described above?

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each test case starts with a single line containing two space-separated integers: P, the number of planets, and W, the number of wormholes. Your home planet is planet 0, and the A.I.'s home planet is planet 1.

The second line of each test case will contain W space-separated pairs of comma-separated integers xi,yi. Each of these indicates that there is a two-way wormhole connecting planets xi and yi.

Output

For each test case, output one line containing "Case #x: c t", where x is the case number (starting from 1), c is the number of planets you conquer if you follow the above strategy, and t is the number of planets you threaten at the end (including the A.I.'s home planet).

Limits

1 ≤ T ≤ 50.
0 ≤ xi < yi < P.
Each wormhole is unique: If i ≠ j, then (xi, yi) ≠ (xj, yj).
There will be at least one way to reach the A.I.'s home planet from your home planet using a series of wormholes.
Memory limit: 1GB.

Small dataset (Test set 1 - Visible)

2 ≤ P ≤ 36.
1 ≤ W ≤ 630.
Time limit: 30 seconds.

Large dataset (Test set 2 - Hidden)

2 ≤ P ≤ 400.
1 ≤ W ≤ 2000.
Time limit: 60 seconds.

Sample

Sample Input
content_copy Copied!
4
2 1
0,1
3 3
0,1 1,2 0,2
5 5
0,4 0,2 2,4 1,2 1,4
7 9
0,6 0,2 0,4 2,4 3,4 2,3 3,5 4,5 1,5
Sample Output
content_copy Copied!
Case #1: 0 1
Case #2: 0 2
Case #3: 1 2
Case #4: 2 4

Explanation

In the first case, you don't have to conquer anything, and you're already threatening the A.I.'s home planet.

In the third case, you can threaten the A.I.'s home planet after conquering only one planet. You end up threatening two planets, and there's an extra planet that isn't connected to anything.

In the fourth case, you can threaten the A.I.'s home planet by conquering planets 4 and 5. You end up threatening planets 6, 2, 3 and 1 (the A.I.'s home planet).

Note

Arcen Games is the creator of A.I. War. Arcen Games does not endorse and has no involvement with Google Code Jam.

Analysis — A. Airport Walkways

Some people will tell you that programming contest problems, while interesting to think about, have no practical use in the real world. After solving this problem, you can laugh at these people as you catch your flight and they are left waiting in line at the airport with all the other chumps.

An important thing to notice about this problem is that the location of the walkways does not matter, since you can instantly transition between different speeds. This means that two walkways with speed v of length L1 and L2 can be combined into a single walkway of length L1 + L2 with speed v. By combining this with the observation that any section of corridor with no walkway is equivalent to a walkway with v = 0, you reduce the problem to having 101 different speed walkways of variable length (possibly 0) and deciding for each whether to run or walk (or do some of each).

The small dataset can be solved by brute force. Let W be the set of all positive length walkways (each with a unique speed). Since there are only |W| ≤ 21 different speed walkways to consider, you can simply try choosing each subset S ⊆ W of them to run (and just walk the rest, W - S). This solution is slightly complicated by the fact that once you choose S, you still have to decide which one to only run partially, in case you don’t have time to run them all fully. However, you can again just brute force this decision by iterating over each walkway x ∈ S and only running on walkway x with whatever time is left after completely running all walkways in S - {x}. You simply take the minimum over all choices, discarding any choice which requires more than t seconds of running time. This can easily be implemented in O(N2 * 2N) and will run in time for N at most 20.
Bonus: Implement this algorithm in O(N * 2N) time.

However, this approach will time out for the large data set, where N is at most 1000 and you can have walkways of all 101 different speeds. For this, we need a better way to decide when to run and when to walk. We just need to decide if it’s better to run on slower or faster walkways. It turns out we can solve this with a simple greedy algorithm, and we can prove it is optimal by using a simple exchange argument.

Let’s say we have two arbitrary walkways of speed w1 and w2, with w1 < w2. Now let’s say that in some algorithm we’ve decided to run for r1 and r2 seconds on each of the walkways, respectively. If s1 and s2 are the amount of time we spent walking on each of the two walkways, then our total time spent would be T = r1 + s1 + r2 + s2 seconds. What if instead we decided to run for r1 + ε seconds on the first walkway and r2 - ε seconds on the second walkway, with ε > 0? Then our total time would be T’ = (r1 + ε) + s1’ + (r2 - ε) + s2 seconds. Solving for T - T’, you will get ε * (w2 - w1) * (R - S) / ((w1 + S) * (w2 + S)) > 0, which says that T > T’, and so the change will always be beneficial. Simply put, it’s always better to run on slower walkways as much as possible. Note that some of the details of these equations have been excluded from this analysis and are left as an exercise to the reader.

Here is some simple Java code which solves the problem:

double res=0;
for (int i=0; i<=100; ++i) {
  double runTime=Math.min(t,W[i]/(i+R));
  double walkDist=W[i]-runTime*(i+R);
  double walkTime=walkDist/(i+S);
  res+=runTime+walkTime;
  t-=runTime;
}
System.out.printf("Case #%d: %.12f%n",TC,res);

Bonus: Solve the problem if the limits changed to 1 ≤ wi ≤ 109.

Test Data
info We recommend that you practice debugging solutions without looking at the test data.

Analysis — B. Spinning Blade

Let us begin by thinking how can we determine the center of mass of a given blade. The simplest formula for the center of mass (obtained by transforming the formula from the problem statement) is: sum(Massi * Pi) / sum(Massi), where Pi is the position of cell i relative to a static location, such as the upper-left corner of the sheet of metal, Massi is the mass of cell i, and i is iterated over all cells in the blade.

The first thing to note about this problem is that the X and Y coordinates of the center of mass can be calculated independently, which will simplify the calculations significantly. The X and Y coordinates of the center of the blade are also easy to calculate (the X coordinate is the average of the smallest and largest X coordinate of any cell in the blade).

The thing we are interested in is whether the center of the blade and the center of mass of the blade coincide. To avoid floating point calculations (which would induce the need to think about possible precision problems) we can multiply the equality sum(Massi * Xi) / sum(Massi) = (minX + maxX) / 2 by the denominators of both sides. Thus, for each blade we need to check the equality 2 * sum(Massi * Xi) = (minX + maxX) * sum(Massi).

So, we simply need to test this equality for all possible blades. This can be done by iterating over all possible X and Y coordinates of the upper-left corner of the blade, and then over all possible sizes of the blade. Calculating either side of the equality above can be performed by iterating over all cells in the blade (remember to omit the corners!). As there are O(RC) possible upper-left corners, O(min(R,C)) possible sizes and O(min(R,C)^2) cells in a blade, the whole algorithm has a time complexity of O(N5) (where N denotes the common upper bound for R and C), which works for the small input, but we cannot expect to make it work for the large.

Before we attack the large case, let us spend a moment to look at potential overflow problems — we already saw that this can be a serious issue in this competition! The left-hand size of the inequality can be estimated by 2 * N2 * N * maxW — two times the number of cells times the largest possible value of Xi times the largest possible weight of a cell. In the small test cases, this value will easily fit into a 32-bit integer, while in the large case we should use 64-bit integers to be safe. We also considered giving a 1018 bound on D, several approaches of dealing with overflow (that can also handle this obscenely large limit) are given at the end of this editorial, you might also want to think about this problem yourself.

Back to the large case. Notice that in the previous approach we have seen there are O(N3) blades to consider, so one approach to reducing the run time is to attempt to make the center of mass calculation for every blade constant. This requires a bit of precalculation.

To precalculate the center of mass (or rather, the sum(Massi * Xi) and sum(Massi) quantities) for any given blade, we will first calculate the center of mass and total mass for all rectangles with the two corners at (0,0) and (x,y). We will start with the rectangle with corners at (0,0) and (1,1). This is just the first cell of the grid, so we already know its center of mass and total mass. We will store this answer and move on to the next rectangle we want to calculate, which will have corners at (0,0) and (1,2). Since we already know the center of mass and total mass for the rectangle with corners (0,0) and (1,1) we can use this rectangle, and the rectangle with corners at (0,1) and (1,2) to calculate the center of mass and total mass for the rectangle with corners (0,0) and (1,2). As long as we iterate over the Y axis 1 by 1 we can calculate the total mass and center of mass of all possible rectangles in constant time.

Now we have to handle the case where we have to iterate the X axis of the corner, so we need to know the center of mass and total mass of the rectangle with corners at (0,0) and (2,1). This is the same as the first case for the Y axis, so we just calculate the center of mass and total mass using the rectangle with corners at (0,0) and (1,1) as well as the rectangle with corners at (1,0) and (2,1). In the next step we run into a problem. We have a grid that looks something like the image below.

If it is not clear in the image, the rectangles marked B and C overlap with the rectangle D.

We know the appropriate sums for the rectangles marked A, B, C, and D, but we need to know the sums for the entire rectangle, which we will call R. This can be done in constant time using:

R = A + B + C - D

We subtract D because it is added twice when we add both B and C.

This can be used to calculate center of mass and total mass both for all rectangles with corners (0,0) and (2,2) on to (X,Y). The total run time for this is O(N2) since we only have to look at each cell once. Now, how can this be used to calculate the sums for a square with corners at (x1,y1) and (x2,y2) (or any other square we might be interested in)? This is very similar to the way we calculated the center of mass and total mass during the precalculations. Assume we label a few of the rectangles we have already precalculated as:

A = Square we are looking for, with corners at (x1,y1) and (x2,y2)

B = Rectangle with corners at (0,0) and (x1,y2)

C = Rectangle with corners at (0,0) and (x2,y1)

R = Rectangle with corners at (0,0) and (x2,y2)

D = Rectangle with corners at (0,0) and (x1,y1)

The same picture, reasoning and equation as before gives us R = A + B + C - D, which transforms to A = R + D - B - C. Thus, having all the precalculations done, we can compute all the needed quantities for any square (and thus, by subtracting the values in the corners, for any blade) in constant time!

With a constant center of mass calculation, this brings the total run time to O(N2 + N3). This will easily work with N <= 500.

Side Note

Another approach to this problem is to try all possible upper-left corners for the blade, and then slowly expand the size of the blade by 1 unit to the bottom-right at a time until it cannot be expanded any further, calculating the required sums using O(N) calculations at each step to increment the previous values. That brings the total run time to O(N4). While this may seem incredibly large when N can be up to 500, in practice this is really a lot less calculations than 5004 (as for most corners we cannot expand up to size N), while the input file size limit guarantees there are at most two max-cases in the input. Thus, this approach will run in time on most computers and in most languages.

Dealing with overflow

Let us go back to the question what would we do if the limit on D was larger.
  1. We can try to use BigIntegers of some sort. This solution costs us in terms of efficiency, although if we go for the O(N3) solution we should still be able to make it.
  2. We can realize that the value of D is irrelevant. On an intuitive level - adding a constant mass D to each cell is the same as putting a new sheet with each cell of mass D on top of our sheet. The center of mass is going to be somewhere in between the centers of mass for the two sheets — and so it is going to be in the middle if and only if our original sheet had the center of mass in the middle. On a formal level, if we add D to each Massi, both sides of the equation increase by 2 * AvgX * NumberOfCells, where AvgX is the average X coordinate of a cell in the blade. Thus, we can set D to, say, 1 and use 32-bit integers
  3. We can also set D to zero. This is somewhat scary, as it would result in a division by zero in the original equation for the center of mass, we encourage you to consider why this works.
  4. Finally, we may ignore the overflow problem totally, if only our compiler guarantees that overflow results in modulo arithmetics. As D cancels out on both sides of the equation anyway, it also cancels out modulo MAXINT, so if only the rest of the equation will not overflow, we will be fine. This requires some knowledge of your tools, though — for instance modular arithmetic for integers in C++ is guaranteed for unsigned integers, but not for signed integers, and the compiler can make optimizations that assume overflow does not happen for signed integers (and thus break code depending on the modular arithmetic).
Test Data
info We recommend that you practice debugging solutions without looking at the test data.

Analysis — C. Expensive Dinner

This problem might look pretty intimidating at first:

  • There are N! possible orders in which your friends could arrive.
  • Not only is O(N!) too slow for this problem, even O(N) is too slow!
  • The actual price your friends are paying will quickly exceed the bounds of a 64-bit integer.

When O(N) is too slow, it means you need to forget about coding for a while and think. You will need some insight to even get started.

Let's begin by fixing an ordering (x1, x2, ..., xN) of your friends. Also let yi be the total price that your group is paying after the first i friends enter, the waiter has been called if necessary, and everyone has become happy.


Observation 1: yi = LCM(x1, x2, ..., xi). This does not depend on the order your friends buy things after the waiter has been called.

Explanation: LCM(x1, x2, ..., xi) is, by definition, the smallest multiple of x1, x2, ..., xi. Since yi must be a multiple of all these numbers for your friends to be happy, it is certainly true that yi ≥ LCM(x1, x2, ..., xi). Conversely, a friend xj would never buy something that skips over a multiple of xj. In particular, none of the friends here would buy something that would skip over LCM(x1, x2, ..., xi). Since yi-1 ≤ LCM(x1, x2, ..., xi), you will eventually reach this price and then stop.


Let M be the number of times the waiter is called over. Then, M is equal to the number of values i in {1, 2, ..., N} such that yi != yi-1. (We define y0 = 0, because the waiter is always called over by the first friend who enters.) So the question becomes: how do we make M as big as possible according to this definition, and how do we make it as small as possible?

Least common multiples are closely related to prime numbers and factorizations, so let's define p1, p2, ..., pP to be the primes less than or equal to N. Also let ei be the largest integer such that piei is less than or equal to N.


Observation 2: Let P' be 1 + sum ei (i.e., the number of prime powers less than or equal to N, including 1). Then the maximum value of M is exactly equal to P'.

Explanation: Suppose your friends arrive in the order 1, 2, ..., N. Then each friend with a prime power index will cause the price to increase, and so the maximum value of M is at least P'.

On the other hand, the price is always a least-common multiple by the first observation, and it always increases to a multiple of itself. In particular, the sum of the exponents in its prime factorization must always go up every time the waiter is called. After the first friend arrives, this sum is at least 0. At the very end, it is equal to P' - 1. Therefore, the waiter can be called at most P' - 1 times after the first person arrives. Combining that with the initial increase proves that MP'.


Observation 3: If N > 1, then the minimum value of M is equal to P.

Explanation: Suppose the first friends to arrive are numbered p1e1, p2e2, ..., pPeP. Then the price is already equal to LCM(p1e1, p2e2, ..., pPeP) = LCM(1, 2, ..., N) after these friends have arrived. This means no subsequent friend will change the total price, and hence M = P in this case.

On the other hand, notice there is no number less than N that is divisible by both piei and pjej. This is because piei and piej are relatively prime and larger than sqrt(N). (If one of them was at most sqrt(N), then its exponent could be increased, which is a contradiction.) Therefore, no single friend can make the total price divisible by two different entries out of {p1e1, p2e2, ..., pPeP}. And so the waiter must be called at least P times, as claimed.


To solve the small input, you can just calculate P and P' directly and go from there. The large input requires one last clever trick. The number of primes less than 1012 is quite large, and you probably cannot afford to just count them all. However, calculating P - P' is actually easier than this!

If you go back to the original definitions, you can see P - P' is precisely the number of integers less than or equal to N that can be written in the form pe for e != 1. When e = 0, you just get 1. When e > 1, then p ≤ 106, and you can easily enumerate all primes of this size! One good way is to use the Sieve of Eratosthenes. As always, you can look at solutions from other contestants to see a full implementation.


Bonus Comment: The Sieve of Eratosthenes runs in O(M * log log M) time, so the simplest implementation of the method described here runs in O(sqrt(N) * T * log log N) time altogether. However, it's worth pointing out that you can do even better. If you pre-compute and sort all prime powers less than 1012 with exponent other than one, you can then use a binary search to very efficiently count how many are less than N for each test case. This is not necessary to solve the problem, but it lets you speed things up even more to a blazing O(sqrt(N) * log log N + T * log N). Proving this running time is a little tricky though!

Test Data
info We recommend that you practice debugging solutions without looking at the test data.

Analysis — D. A.I. War

The computer game A.I. War hides at least a few good algorithmic problems. The author is anything but an expert, but musing about the game brought both this problem and Space Emergency (which originally took place on a graph like this one) to life. The game presents a trickier version of this problem: there are two A.I. homeworlds, multiple other planets that you might want to visit, and you don't know where to find any of them at the start of the game. Fortunately, here we're dealing with a simplified version of the problem and you didn't have to know anything about the game.

Let's first state the problem in graph theory terms. We are given an undirected graph with P vertices and W edges. We are looking for a sequence of vertices, starting with vertex 0 (our home planet) and ending with a neighbor of 1 (A.I.'s home planet), such that:

  • every vertex in the sequence is adjacent to one of the previous vertices
  • the sequence is as short as possible
  • given the above, the number of distinct neighbors of the vertices in the sequence, but outside the sequence, must be as large as possible

Let D be the distance from vertex 0 to vertex 1. It's clear that every such sequence must have at least D elements. We also note that we will achieve exactly D elements if and only if the sequence forms a shortest path from vertex 0 to vertex 1. Hence we're looking for a shortest path. Unfortunately, there may be many shortest paths and we have to pick the one that optimizes the last requirement.

It simplifies things to include among the "threatened" planets those planets that we do conquer. Given that we already know that we have to conquer exactly D planets, we just have to subtract D at the end.

Crucial observation

The crucial observation for solving the problem is the following: if a vertex is at distance d from 0, it can only be threatened by a vertex at distance d - 1, d or d + 1. This is true because the distances of two adjacent vertices differ by at most 1. Therefore every vertex in the graph is only threatened (or conquered) within at most three consecutive vertices in the path. As we will see, this observation allows us to use dynamic programming to compute best paths of larger and larger lengths.

The algorithm

The first step in our algorithm is to run breadth-first search to compute for every vertex v its distance from 0: dist[v]. dist[0] = 0 and dist[1] = D. Every shortest path will start with vertex 0, then continue with vertices at distance 1, distance 2, ..., distance D-1.

For any two adjacent vertices a, b such that dist[b] = dist[a] + 1, define F(a, b) = the maximum number of planets threatened or conquered by a shortest path 0→...→ab. We will compute this using dynamic programming for increasing distances from 0. The answer to the problem is the maximum value of F(a, b) - D, where a, b are adjacent, dist[a] = D-2, dist[b] = D-1, and b is adjacent to 1.

F(0, a) can be computed directly (there is only one path possible). It remains to compute the values of F for a given distance, given the values of F at a previous distance. To compute F(b, c), dist[b]=d, dist[c]=d + 1, try all vertices a adjacent to b such that dist[a] = d - 1. In other words, we are looking for paths ending with abc. We have already computed the value of F(a, b) in the previous iteration, the question is: how many new unique threatened vertices does extending the path to c add?

This is where our "crucial observation" becomes useful. If a neighbor of c was already threatened (or conquered) before, it must have been a neighbor of either a or b. Therefore we must add the number of neighbors of c that are not neighbors of either a or b. Let's call this value G(a, b, c). So we have the recursive formula that we can use for dynamic programming:
F(b, c) = maxa F(a, b) + G(a, b, c).

Computing G: four algorithms

We are almost done, but how do we compute the values of G, and what is the total run-time of the algorithm? There are O(W) values of F to compute (at most one for each edge), and for each one we look at O(P) other values of F (one for each a). So if we already knew all the values of G, it would take O(PW) time to compute all the values of F and solve the problem. Computing the values of G turns out to be the most time-consuming part though.

We may have to compute G(a, b, c) for every sub-path abc of increasing dist. How do we compute these values? We have thought of at least 4 ways. In the actual contest it didn't really matter which you chose, all would easily run in time, but we will mention them just for fun.

  • Approach 1. We need to compute the number of vertices v such that v is a neighbor of c, but not of a or b. The simplest approach here is to just check this condition for every v. This computation takes O(P) time. How many values do we need to compute? At most O(P3), which gives a total run-time of O(P4) for the whole algorithm. We can give a better estimate. Since a and b are neighbors, there are at most W such pairs. This gives the total run-time of O(P2 W).
  • Approach 2. Modify approach 1 slightly. Instead of checking every vertex v, we only need to check every neighbor of c. This way there are O(W) pairs a, b and O(W) pairs c, v, which gives the total run-time of O(W2).
  • Approach 3. Modify approach 1 in another way. Precompute the set of neighbors of each vertex as a bitmask neighbors[v]. Now we are simply interested in the number of bits set in (neighbors[c] and not (neighbors[a] or neighbors[b]). This is a speedy computation due to bit-level parallelism. If our computer has machine words of size w (this is typically 32 or 64), we cut our work by a factor of w. This assumes that we can count the number of bits set in a word in a single step, which modern processors support in a single machine instruction. The final runtime: O(P2 W / w).
  • Approach 4. Finally, we come to a theoretically interesting, but rather complex to implement aproach. Define two matrices, A of size W x P, and B of size P x P, as follows. Aij = 1 if vertex number j does not neighbor any of the two endpoints of the edge number i, 0 otherwise. Bij = 1 if vertices number i, j are adjacent (or equal), 0 otherwise. Now compute the matrix product C = A * B. If we apply the definition of matrix product and do the math, we will see that C is a W x P matrix and that the entries are exactly the values of G. Specifically, Cij = G(a, b, j) if the i-th edge is ab.
    If we evaluate the matrix product in the natural way, we get the same complexity as in approach 1: O(P2 W). We have basically expressed approach 1 in matrix notation.
    The trick is that there are faster matrix multiplication algorithms. The fastest currently known is the Coppersmith-Winograd algorithm. To make a long story short, it gives us a theoretical asymptotic run-time of O(P1.376 W).

We do not recommend the last approach in the contest. Not only is this unnecessarily complicated, it also wouldn't actually run any faster for the graph sizes we are considering. The asymptotic advantage would only materialize for impractically enormous, dense graphs.

Test Data
info We recommend that you practice debugging solutions without looking at the test data.

Statistics — A. Airport Walkways

Test set 1: 2130 correct solutions (94.8% solve rate)

First
winger Java, 10:34
misof C++, 11:05
peter50216 11:26
nika C++, 11:30
mikhailOK Java, 11:33
Shortest
espes Python, 452 bytes
shubhtuls C++, 514 bytes
kusano Python, 520 bytes
zibada Python, 560 bytes
chuanren Python, 597 bytes

Test set 2: 2075 correct solutions (92.4% solve rate)

First
winger Java, 10:34
misof C++, 11:05
peter50216 11:26
nika C++, 11:30
mikhailOK Java, 11:33
Shortest
NateSullivan Java, 382 bytes
espes Python, 452 bytes
chuanren Python, 519 bytes
kusano Python, 520 bytes
zibada Python, 560 bytes

Statistics — B. Spinning Blade

Test set 1: 1363 correct solutions (60.7% solve rate)

First
mystic Java, 20:44
winger Java, 23:47
mikhailOK Java, 27:31
ACRush aka ACRushTC 32:22
victorbarinov 33:53
Shortest
zibada Python, 718 bytes
.dP. Python, 799 bytes
Ebonnov Python, 861 bytes
jbochi Python, 865 bytes
fura2 C++, 887 bytes

Test set 2: 516 correct solutions (23.0% solve rate)

First
mystic Java, 20:44
winger Java, 23:47
mikhailOK Java, 27:31
ACRush aka ACRushTC 32:22
victorbarinov 33:53
Shortest
battyone C++, 1265 bytes
BM954 C++, 1357 bytes
Yao C, 1395 bytes
Milanin C++, 1480 bytes
Bright C++, 1483 bytes

Statistics — C. Expensive Dinner

Test set 1: 780 correct solutions (34.7% solve rate)

First
omeometo C++, 18:01
meret C++, 18:30
rng_58 aka rng..58 C++, 19:01
hos.lyric D, 23:41
tourist aka Gennady.Korotkevich Pascal, 28:11
Shortest
siunausli -, 394 bytes
aryan.9001 C++, 417 bytes
shubham.mittal Ruby, 430 bytes
Milanin C++, 431 bytes
SmartSchizo C++, 440 bytes

Test set 2: 491 correct solutions (21.9% solve rate)

First
omeometo C++, 18:01
meret C++, 18:30
rng_58 aka rng..58 C++, 19:01
hos.lyric D, 23:41
tourist aka Gennady.Korotkevich Pascal, 28:11
Shortest
Milanin C++, 431 bytes
SmartSchizo C++, 453 bytes
Ra16bit C++, 466 bytes
.dP. Python, 478 bytes
dzetkulict C++, 501 bytes

Statistics — D. A.I. War

Test set 1: 261 correct solutions (11.6% solve rate)

First
austrin C++, 28:44
winger Java, 51:30
RiOrius Python, 54:41
canton 60:03
Ilod Java, 62:19
Shortest
uaedante C++, 941 bytes
abiczo Python, 1045 bytes
ditzone Python, 1073 bytes
monsoon C++, 1097 bytes
unbe Python, 1129 bytes

Test set 2: 87 correct solutions (3.9% solve rate)

First
austrin C++, 28:44
ACRush aka ACRushTC 67:08
mystic Java, 76:09
meret C++, 77:37
wata Java, 77:37
Shortest
sisu C++, 1742 bytes
eMBe C++, 1746 bytes
gawry C++, 1925 bytes
Vitaliy C, 1931 bytes
Vytis C++, 2024 bytes