DEV Community

Cover image for Remove terrible bus routes (find an algorithm)

Remove terrible bus routes (find an algorithm)

Håvard Krogstie on March 09, 2019

Here is a challenge for those who want to do some algorithms programming, similar to what you would find in algorithms competitions, such as the IO...
Collapse
 
choroba profile image
E. Choroba

Perl solution, inserting each line into the final array right after having read it. Implementing the binary search myself.

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

<>; # Ignore the size, just process all the lines.

my @good;
while (<>) {
    my ($leave, $arrive) = split;

    # Binary search.
    my ($from, $to) = (0, $#good);
    while ($from < $to) {
        my $middle = int(($from + $to) / 2);
        if ($good[$middle][0] < $leave) {
            $from = $middle + 1;
        } else {
            $to = $middle;
        }
    }
    my $new = $from + (@good && $good[-1][0] < $leave);

    if ($new < $#good && $good[$new][0] == $leave) {
        $good[$new][1] = $arrive if $arrive < $good[$new][1];
        next
    }

    if ($new > $#good || $arrive < $good[$new][1]) {
        splice @good, $new, 0, [$leave, $arrive];

        if ($new) {
            my $before = $new;
            do { --$before } while $before && $good[$before][1] >= $arrive;
            splice @good, $before + 1, $new - $before - 1;
        }
    }
}

say scalar @good;
say "@$_" for @good;
Collapse
 
hkrogstie profile image
Håvard Krogstie

Python

Complexity O(nlog n)

#!/bin/env python3

n = int(input())
trips = []
for _ in range(n):
    times = input().split(' ')
    trips.append((int(times[0]), int(times[1])))

# Sort by decreasing arrive_time when the leave_time is the same
trips.sort(key=lambda x:x[1], reverse=True)
# By increasing leave_time
trips.sort(key=lambda x:x[0])

# Remove duplicates
trips = [trips[0]] + [b for a,b in zip(trips, trips[1:]) if a!=b]
stack = []
for trip in trips:
    while stack and stack[-1][1] >= trip[1]:
        #The trip on the stack is worse than trip
        stack.pop()
    stack.append(trip)

print(len(stack))
for a, b in stack:
    print(a, b)

Explanation

The stack contains trips not yet determined to be bad. The trips are processed in ascending leave_time. This means any trip already on the stack, has a lower or equal leave_time than the trip we are currently looking at.

If the trip on the top of the stack arrives later than the current trip,
that means the trip on the stack starts earlier and ends later
than the current trip. Therefore the stack trip is worse, and is popped off the stack.

This is repeated until the trip on the top of the stack ends before the current trip.
At that point, all trips down the stack are safe, because
no trip further down the stack ends after the top trip.
After the stack-popping is done, we add the current trip.

If multiple trips start at the same time, the one
with the larger arrive_time comes first, because
it needs to be popped by the better trip, when it comes later.
The sorting we do at the start makes sure
that a trip always comes before the trip it is objectively worse than.
This means the last trip is guaranteed to be good.

Collapse
 
choroba profile image
E. Choroba

Why is 27 40 not part of the solution 2?

Collapse
 
hkrogstie profile image
Håvard Krogstie • Edited

Ok, there is not an issue with the program, but the test input, rather. The first line says 20, when there are 30 trips to read. Fixed.

Collapse
 
hkrogstie profile image
Håvard Krogstie

That's a very good question! I'll debug my program right after breakfast.

Collapse
 
detunized profile image
Dmitry Yakimenko

Have you tested on the maximal N = 1e6 as stated in the problem description? Your solution seems to be O(N*N) so it will be really slow.

Collapse
 
hkrogstie profile image
Håvard Krogstie

One possibility is comparing every pair of trips to see if one is objectively worse than another, but that would take a long time if N were the theoretical maximum of 100000.