One-way flight trip problem

后端 未结 18 1504

You are going on a one-way indirect flight trip that includes billions an unknown very large number of transfers.

  • You are not stoppi
18条回答
  •  星月不相逢
    2020-12-12 17:51

    I have written a small python program, uses two hash tables one for count and another for src to dst mapping. The complexity depends on the implementation of the dictionary. if dictionary has O(1) then complexity is O(n) , if dictionary has O( lg(n) ) like in STL map, then complexity is O( n lg(n) )

    import random
    # actual journey: a-> b -> c -> ... g -> h
    journey = [('a','b'), ('b','c'), ('c','d'), ('d','e'), ('e','f'), ('f','g'), ('g','h')]
    #shuffle the journey.
    random.shuffle(journey)
    print("shffled journey : ", journey )
    # Hashmap to get the count of each place
    map_count = {}
    # Hashmap to find the route, contains src to dst mapping
    map_route = {}
    
    # fill the hashtable
    for j in journey:
        source = j[0]; dest = j[1]
        map_route[source] = dest
        i = map_count.get(source, 0)
        map_count[ source ] = i+1
        i = map_count.get(dest, 0)
        map_count[ dest ] = i+1
    
    start = ''
    # find the start point: the map entry with count = 1 and 
    # key exists in map_route.
    for (key,val) in map_count.items():
        if map_count[key] == 1 and map_route.has_key(key):
            start = key
            break
    
    print("journey started at : %s" % start)
    route = [] # the route
    n = len(journey)  # number of cities.
    while n:
        route.append( (start, map_route[start]) )
        start = map_route[start]
        n -= 1
    
    print(" Route : " , route )
    

提交回复
热议问题