Exemple #1
0
def kruskal(dist, N, st):
    tree = UnionFind(N)
    relation = [[] for i in range(N)]
    one_array_dist = list(itertools.chain.from_iterable(dist))
    for k in np.argsort(one_array_dist):
        i = k % N
        j = int(k / N)
        if not tree.issame(i, j) and len(relation[i]) < 2\
           and len(relation[j]) < 2:
            relation[i].append(j)
            relation[j].append(i)
            tree.unite(i, j)

    def go_next():
        for i in range(len(relation[next_city])):
            if relation[next_city][i] in unvisited_cities:
                return relation[next_city][i]
        return None

    edge = []
    for i in range(N):
        if len(relation[i]) == 1:
            edge.append(i)
    relation[edge[0]].append(edge[1])
    relation[edge[1]].append(edge[0])

    current_city = st
    unvisited_cities = set(range(0, N))
    tour = [current_city]
    unvisited_cities.remove(current_city)

    next_city = relation[current_city][0]
    while unvisited_cities:
        unvisited_cities.remove(next_city)
        tour.append(next_city)
        next_city = go_next()

    return tour
Exemple #2
0
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for i in range(m)]

from unionfind import UnionFind

ans = 0
for i in range(m):
    uf = UnionFind(n)
    for j, abi in enumerate(ab):
        # ai,biの辺を除いたグラフでunionfindを構築
        if j == i: continue
        a, b = abi
        uf.unite(a, b)
    a, b = ab[i]
    # ai,bi 間の辺を除いた状態で ai,biは同じグループか?(親は存在するか)
    # 親がいなければ, 非連結 -> ai,bi間のへんしか存在しないことになる
    if not uf.issame(a, b):
        ans += 1
print(ans)