Google Hash Code Competition Summary

2022-03-17 19:30:19 浏览数 (2)

感想

迷失在了历史的长河中。Lost in time.

Key code

main.py

代码语言:javascript复制
from math import ceil

from helpers import IO
from typing import Dict, List


class Task:
    def __init__(self, duration: int, num_intersections: int, num_streets: int, num_cars: int, bonus: int):
        self.duration = duration
        self.num_intersections = num_intersections
        self.num_streets = num_streets
        self.num_cars = num_cars
        self.bonus = bonus
        self.all_streets: Dict[str, Street] = dict()
        self.all_intersections: List[Intersection] = [Intersection(i) for i in range(num_intersections)]
        self.all_cars: List[Car] = []


class Street:
    def __init__(self, begin: int, end: int, name: str, length: int):
        self.begin = begin
        self.end = end
        self.name = name
        self.length = length
        task.all_intersections[end].incoming.append(self.name)
        self.cars: List[Car] = []
        self.greenCarCounts = 0

    def __repr__(self):
        return f"S {self.name}: {self.length}"


class Intersection:
    def __init__(self, index: int):
        self.index = index
        self.incoming: List[str] = []
        # self.outgoing = []

    def __repr__(self):
        return f"I {self.index}: {self.incoming}"


# def assignAllIncoming():
#     return none


class Car:
    def __init__(self, index: int, number: int, streets: List[str]):
        self.index = index
        self.number = number
        self.streets = streets
        self.length = sum([task.all_streets[street].length for street in streets])
        self.reached = True
        self.passingstreet = streets[0]
        self.passedstreet = 0
        self.reachedstreet = None

    def __repr__(self):
        return f"C {self.index}: {self.length}"

    """def status_update(self):
        self.currentlength    
        if self.currentlength == self.passingroad.length:
            self.reached = True
            self.passedstreet    
            self.reachedstreet = self.passingstreet
            self.passingstreet = self.streets[self.passedstreet]
        else:
            self.reached = False
            self.reachedstreet = None"""


def main():
    # IO setting
    code_io = IO()
    listName = ['a', 'b', 'c', 'd', 'e', 'f']
    for filename in listName:
        code_io.set_file_in("./tasks/" filename ".txt")
        code_io.set_file_out("./results/" filename ".txt")
        global task
        D, I, S, V, F = code_io.readline_tuple(int)
        task = Task(D, I, S, V, F)
        for _ in range(S):
            B, E, Name, L = code_io.readline_tuple(str)
            task.all_streets[Name] = Street(int(B), int(E), Name, int(L))
        for i in range(V):
            Line = code_io.readline_array(str)
            task.all_cars.append(Car(i, int(Line[0]), Line[1:]))

        arr = sorted(task.all_cars, key=lambda car: car.length)
        """
        for intersection in task.all_intersections:
            greencarlist = [0]*len(intersection.incoming)
            for i in range(D):
                for cars in task.all_cars:
                    cars.update_status()
                    if cars.reachedstreet in intersection.incoming:
                        if arr.index(cars) < greenCar:
                            greenCar = arr.index(cars)
                for street in intersection.incoming:
                    if street.name==arr[greenCar].reachedstreet:
                        greencarlist[intersection.index(street)] =1
                sum(greencarlist)"""

        counter = 0
        for cars in arr:
            for street in cars.streets:
                task.all_streets[street].greenCarCounts  = 1
                counter  = task.all_streets[street].length
            if counter > task.duration:
                break

        code_io.write(len(task.all_intersections))
        for intersection in task.all_intersections:
            code_io.write(intersection.index)
            code_io.write(len(intersection.incoming))
            ratio = sum([task.all_streets[street].greenCarCounts for street in intersection.incoming]) / task.duration
            for street in intersection.incoming:
                if (int(ceil(task.all_streets[street].greenCarCounts * ratio))) > task.duration:
                    code_io.write(street   " "   str(task.duration))
                else:
                    code_io.write(street   " "   str(1   int(ceil(task.all_streets[street].greenCarCounts * ratio))))
        code_io.flush()

        # print(arr)
        # print(task.all_intersections)
        # code_io.write(len(task.all_intersections))
        # for intersection in task.all_intersections:
        #     code_io.write(intersection.index)
        #     code_io.write(len(intersection.incoming))
        #     for street in intersection.incoming:
        #         code_io.write(street   " 1")
        # code_io.flush()


if __name__ == '__main__':
    main()

"""
This is the algo
for time in range(totaltime):
	for cars in all_cars:
		cars.update_status()
	for intersection in all_intersections:
		for all cars waiting at this intersection:
			turn the green light for the car with the smallest index in the array to green
            record the green light change for this intersection ID

def update_status:
	current_road =1
	if current_road==crossingroad.length():
		waiting=crossingroad
        current_road=0

def cost():
    return (length of remaining route   remaining intersection * itsweight
"""

helper.py

代码语言:javascript复制
import io
import sys
import time


class IO:
    def __init__(self):
        self.stdin = sys.stdin
        self.stdout = sys.stdout
        self.buffer = io.StringIO()

    def set_stdin(self):
        self.stdin = sys.stdin

    def set_stdout(self):
        self.stdout = sys.stdout

    def set_stdio(self):
        self.set_stdin()
        self.set_stdout()

    def set_file_in(self, file_name):
        self.stdin = open(file_name, "r")

    def set_file_out(self, file_name):
        self.stdout = open(file_name, "w")

    def set_file(self, file_name):
        self.set_file_in(file_name)
        self.set_file_out(file_name   time.strftime("_%H_%M_%S", time.gmtime())   ".txt")

    def readline(self, type_=str):
        return type_(self.stdin.readline().strip())

    def readline_tuple(self, type_=str):
        return map(type_, self.readline().split())

    def readline_array(self, type_=str):
        return list(self.readline_tuple(type_))

    def write(self, var, end="n"):
        self.buffer.write(str(var)   end)

    def write_array(self, arr, sep=" ", end="n"):
        self.buffer.write(sep.join(map(str, arr))   end)

    def flush(self):
        self.stdout.write(self.buffer.getvalue())
        self.buffer = io.StringIO()

def scoring():
    pass

0 人点赞