Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8356109
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T10:04:58+00:00 2026-06-09T10:04:58+00:00

For an algorithm competition training (not homework) we were given this question from a

  • 0

For an algorithm competition training (not homework) we were given this question from a past year. Posted it to this site because the other site required a login.

This is the problem:
http://pastehtml.com/view/c5nhqhdcw.html

Image didn’t work so posted it here:

It has to run in less than one second and I can only think about the slowest way to do it, this is what I tried:

with open('islandin.txt') as fin:
    num_houses, length = map(int, fin.readline().split())
    tot_length = length * 4 # side length of square
    houses = [map(int, line.split()) for line in fin] # inhabited houses read into list from text file

def cost(house_no):
    money = 0
    for h, p in houses:
        if h == house_no: # Skip this house since you don't count the one you build on
            continue
        d = abs(h - house_no)
        shortest_dist = min(d, tot_length - d)    
        money += shortest_dist * p
    return money


def paths():
    for house_no in xrange(1, length * 4 + 1):
        yield house_no, cost(house_no)
        print house_no, cost(house_no) # for testing

print max(paths(), key=lambda (h, m): m) # Gets max path based on the money it makes

What I’m doing at the moment is going through each location and then going through each inhabited house for that location to find the max income location.

Pseudocode:

max_money = 0
max_location = 0
for every location in 1 to length * 4 + 1
    money = 0
    for house in inhabited_houses:
        money = money + shortest_dist * num_people_in_this_house
    if money > max_money
        max_money = money
        max_location = location

This is too slow since it’s O(LN) and won’t run in under a second for the largest test case. Can someone please simply tell me how to do it in the shortest run time (code isn’t required unless you want to) since this has been bugging me for ages.

EDIT: There must be a way of doing this in less than O(L) right?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T10:05:02+00:00Added an answer on June 9, 2026 at 10:05 am

    Suppose the list houses is composed of pairs (x,pop) with 0 <= x < 4*L the location and pop the population.

    The objective function, which we want to maximize, is

    def revenue(i):
        return sum(pop * min((i-j)%(4*L), 4*L - (i-j)%(4*L)) for j,pop in houses)
    

    The naive algorithm O(LN) algorithm is simply:

    max_revenue = max(revenue(i) for i in range(4*L))
    

    But it is incredibly wasteful to entirely re-evaluate revenue for each location.

    To avoid that, notice that this is a piecewise-linear function; so its derivative is piecewise constant, with discontinuities at two kinds of points:

    • at house i, the derivative changes from slope to slope + 2*population[i]
    • at the point located opposite house i on the island, the derivative changes from slope to slope - 2*population[i]

    This makes things very simple:

    1. We only have to examine actual houses or opposite-of-houses, so the complexity drops to O(N²).
    2. We know how to update the slope from house i-1 to house i, and it requires only O(1) time.
    3. Since we know the revenue and the slope at location 0, and since we know how to update the slope iteratively, the complexity actually drops to O(N): between two consecutive houses/opposite-of-houses, we can just multiply the slope by the distance to obtain the difference in revenue.

    So the complete algorithm is:

    def algorithm(houses, L):
        def revenue(i):
            return sum(pop * min((i-j)%(4*L), 4*L - (i-j)%(4*L)) for j,pop in houses)
    
        slope_changes = sorted(
                [(x, 2*pop) for x,pop in houses] +
                [((x+2*L)%(4*L), -2*pop) for x,pop in houses])
    
        current_x = 0
        current_revenue = revenue(0)
        current_slope = current_revenue - revenue(4*L-1)
        best_revenue = current_revenue
    
        for x, slope_delta in slope_changes:
            current_revenue += (x-current_x) * current_slope
            current_slope += slope_delta
            current_x = x
            best_revenue = max(best_revenue, current_revenue)
    
        return best_revenue
    

    To keep things simple I used sorted() to merge the two types of slope changes, but this is not optimal as it has O(N log N) complexity. If you want better efficiency, you can generate in O(N) time a sorted list corresponding to the opposite-of-houses, and merge it with the list of houses in O(N) (e.g. with the standard library’s heapq.merge). You could also stream from iterators instead of lists if you want to minimize memory usage.

    TLDR: this solution achieves the lowest feasible complexity of O(N).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is the Kahan summation algorithm from Wikipedia : function KahanSum(input) var sum =
This question is to discuss how to code a spell corrector and is not
I recently took part in ACM certified programming competition. This is the question which
EDIT: This is not a question on how I can programatically set expiration. I
Algorithm to generate all possible letter combinations of given string down to 2 letters
The algorithm is described in this paper: Thread Scheduling for Multiprogrammed Multiprocessors . Briefly,
What algorithm would you suggest to identify how much from 0 to 1 (float)
I am looking for a compression algorithm (for a programming competition) and I need
I am stuck with one of the algorithm homework problem. Can anyone give me
I don't know much about color composition, so I came up with this algorithm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.