SRM 817, D2, 500-Pointer (Gym)

James S. Plank

Thu Nov 4 00:18:25 EDT 2021

In case topcoder's servers are down

Here's a summary of the problem:

Examples:

#      M      N      T  Answer and comments.
- ------ ------ ------ --------------------------------------------
0     47     10   1000  10: There are more machines than people.
1      1     10   1000   3: People 0, 1 and 3 can workout.
2      1     10      1  10: Everyone only works out for 0.5 seconds.
3      2     10    100  10: People 0, 1, 2, 3 and 7 can workout.
4     15    100     47  82: No comment.

Testing yourself

I have a shell script tests.sh, that you can use to test your program. When you run tests.sh, your answer should be identical to answers.txt.

Hints

If we were to simulate this, how would we do it?

Obviously, we iterate on the people, from 0 to N-1. That's O(N).

For each person, we see if there's a machine available. If so, we allocate the machine, and calculate when it will be free again. We also add one to the return value. If there's no machine available, then we move on.

So, how should we "allocate the machine." My recommendation is to use a multiset, keyed on the time when the machine will be free. To avoid floating point, I inserted the time minus 0.5. Then, my loop went as follows:

for (i = 0; i < N; i++) {
  if (the machines multiset has less than N elements) {
    add one to the return value
    add the finishing time (minus 0.5) to the multimap
  } else {
    do nothing
  }
  for all machines that are finished at time i, remove them from the multimep
}
What's the running time? It's O(N log(N)) -- O(N) for the loop and O(log N) for the multimap operations. With N capped at 300,000, this is fast enough for topcoder.