道路和图书馆在python中使用BFS

时间:2018-07-18 19:04:16

标签: python data-structures graph graph-algorithm breadth-first-search

我在Hackerrank中遇到了Roads and Libraries问题,这是我在python中的解决方案。我使用邻接表来表示图,并使用广度优先搜索来遍历图,但是大多数测试用例由于超时而失败。如何提高代码效率?

def bfs(i, n, E, level):

    #level = [-1] * (n+1)
    queue = []
    level[i] = 0
    queue.append(i)
    vertices = 1

    #print(E)
    while len(queue) > 0:
        head = queue[0]
        queue = queue[1:]
        for k in E[head]:
            if level[k] == -1:
                level[k] = 1 + level[head]
                queue.append(k)
                vertices += 1

    return level, vertices


q = int(input())
for case in range(q):
    e = input().split(" ")
    n = int(e[0])
    m = int(e[1])
    clib = int(e[2])
    croad = int(e[3])
    E = {}
    comp = 0
    edges_per_comp = []
    level = [-1]*(n+1)

    for i in range(1, n+1):
        E[i] = []

    for edge in range(m):
        e = input().split(" ")
        u = int(e[0])
        v = int(e[1])
        E[u].append(v)
        E[v].append(u)

    s = 1
    while True:
        flag = 0
        #vertices = 0
        level, vertices = bfs(s, n, E, level)
        #print(level)
        for i in range(1,n+1):
            if level[i] == -1:
                s = i
                flag = 1
                break

        edges_per_comp.append(vertices-1)
        if flag == 0:
            break;

    comp = len(edges_per_comp)
    #print(edges_per_comp)

    if clib < croad:
        print(clib*n)
    else:
        print(croad*sum(edges_per_comp)+comp*clib)

0 个答案:

没有答案