减少时间复杂性

时间:2018-06-03 07:52:49

标签: python python-3.x performance optimization shortest-path

我正在尝试解决https://www.codechef.com/INOIPRAC/problems/INOI1402并获得'运行时错误(NZEC)'。如何让它更优化? 我试过Djikstra,但仍然是同样的问题。

任何人都可以帮助我,感谢你的时间。

以下是我的代码,

c,f = map( int, input().split())
routes_array = []

#c = 4
#f = 5 
#routes_array = [{'end': 2, 'start': 1, 'price': 10}, {'end': 3, 
'start': 1, 'price': 24}, {'end': 3, 'start': 2, 'price': 2}, {'end': 
4, 'start': 2, 'price': 15}, {'end': 4, 'start': 3, 'price': 7}]

start_location = 1
end_location = c 

def get_cheapest_price():
    _list_starting_routes = []
    for i in range(0, len(routes_array)):
        if start_location == routes_array[i]['start']:
            _list_starting_routes.append(routes_array[i])

    _list_of_routes = []
    for j in range(0, len(_list_starting_routes)):
        if _list_starting_routes[j]['end'] == end_location :
            _list_of_routes.append([_list_starting_routes[j]])
        else:
            _route = get_points(_list_starting_routes[j], 
end_location, routes_array)
            _list_of_routes.append(_route)              
    return _list_of_routes

def get_points(routes, _end, routes_array, path = []):
    path = path + [routes]
    if (routes['end'] == _end):
        return path
    else:
        for i in range(0, len(routes_array)):
            if (routes['end'] == routes_array[i]['start']):
                get_paths = get_points(routes_array[i], _end, 
routes_array, path)
                if get_paths:
                    return get_paths    


def get_data():
    for i in range(0,f):
        _start, _end, _price = map(int, input().split())
        _routes = {}
        _routes['start'] = _start
        _routes['end'] = _end
        _routes['price'] = _price
        routes_array.append(_routes)

def get_price_for_route(array):
    return sum(array[i]['price'] for i in range(len(array)))  


get_data()
result = get_cheapest_price()
if(len(result) ==1):
   print(get_price_for_route(result[0]))
else:
   print(min(get_price_for_route(a) for a in result))

0 个答案:

没有答案