Google Code Jam - Space Emergency
Space Emergency is a nice little puzzle from Google Code Jam 2011.
The solution is quite simple. Fly as long as the boosters are built. Once they are done, reorder your remaining distance. Use the boosters on longest distances. Voila - that's it.
Let’s see the straight forward implementation for the small input.
- for (int casenr = 1; casenr <= testcases; casenr++) {
- Integer time = 0;
- Integer boosters = scanner.nextInt(); // L
- long buildTime = scanner.nextLong(); // t
- Integer finalStar = scanner.nextInt(); // N
- Integer stars = scanner.nextInt(); // C
- List<Integer> distances = new ArrayList<Integer>();
- for (int i = 0; i < stars; i++) {
- distances.add(scanner.nextInt() * 2);
- }
- // lay out the track we'll travel
- List<Integer> track = new ArrayList<Integer>();
- for (int i = 0; i < finalStar; i++) {
- track.add(distances.get(i % distances.size()));
- }
- // let the ship fly till the boosters are ready
- while (track.size()>0 && track.get(0) <= buildTime) {
- time += track.get(0);
- buildTime -= track.get(0);
- track.remove(0);
- }
- // check if we're between two planets when the boosters are ready
- if (track.size() > 0 && buildTime > 0) {
- time += (int) buildTime;
- track.set(0, track.get(0) - (int)buildTime);
- }
- // reorder by distance use boosters on longest distance until we're out of boosters
- Collections.sort(track);
- Collections.reverse(track);
- while (track.size() > 0) {
- if (boosters > 0) {
- time += track.get(0) / 2;
- track.remove(0);
- boosters--;
- } else {
- time += track.get(0);
- track.remove(0);
- }
- }
- System.out.printf("Case #%d: %s\n", casenr, time);
- out.printf("Case #%d: %s\n", casenr, time);
- }
- }
Do you trust this to handle this code to handle the large input?
There’s one minor arithmetic error and one major performance problem in the given solution. Take a few seconds and try to spot them.
If you think you did, continue on page two to see the solution.
- Login to post comments