Created
May 4, 2013 18:30
-
-
Save xtoss/5518303 to your computer and use it in GitHub Desktop.
My solution for Google code jam 2013 Round 1B - Problem A - Osmos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Used to solve google code jam 2013 Round 1B - Problem A - Osmos | |
Owner: Jamie Xu - [email protected] | |
""" | |
def osmos(): | |
""" | |
File Handle | |
""" | |
in_f = open('A-large.in', 'r') | |
out_f = open('output.txt', 'w') | |
num_of_case = int(in_f.readline().rstrip('\n')) | |
for i in range(1, num_of_case+1): | |
solve_case(in_f, out_f, i) | |
def solve_case(in_f, out_f, case_index): | |
""" | |
Fetch case info | |
""" | |
# print "start handling case #{}".format(case_index) | |
case_info = in_f.readline().rstrip('\n').split(" ") | |
init_size = int(case_info[0]) | |
N = int(case_info[1]) | |
line = in_f.readline().rstrip('\n') | |
num_list = line.split(" ") | |
for x in xrange(0, N): | |
num_list[x] = int(num_list[x]) | |
num_list.sort() | |
min_steps = get_min_steps(0, init_size, num_list) | |
out_f.write("Case #{}: {}\n".format(case_index, min_steps)) | |
def get_min_steps(current_steps, current_size, re_list): | |
""" | |
Recursive function used to get minimum steps to sovle Osmos game. | |
""" | |
# print "Debug:{} {} {}".format(current_steps, current_size, remaining_list) | |
# accept your miserable fate. | |
if current_size <= 1: | |
return current_steps + len(re_list) | |
# eat every edible number | |
while len(re_list) > 0 and current_size > re_list[0]: | |
current_size = current_size + re_list.pop(0) | |
length = len(re_list) | |
if length == 0: | |
return current_steps | |
# add the biggest_edible_number(= current_size - 1) and continue | |
min_step_by_adding_number = get_min_steps(current_steps + 1, current_size * 2 -1 , re_list) | |
# once you start to remove the smallest number, there is no way that you could achieve a less steps by adding numbers later than just removing all of the remaining numbers. | |
min_step_by_removing_number = current_steps + length | |
return min(min_step_by_adding_number, min_step_by_removing_number) | |
if __name__ == '__main__': | |
osmos() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment