簡體   English   中英

有向圖的最大簡單循環

[英]Maximum Simple Cycle in Directed Graph

圖中的最大簡單周期(乘積)

你好,

我構造了一個有向圖G =(v,e),我想在此圖中找到最大的簡單循環,在該循環中,邊權重被相乘而不是相加。 我這樣做的最初方法是構造一個新圖G =(v,e'),其中e'(i,j)= 1 / e(i,j)/ min(e'),然后應用Floyd-Warshall在此圖上查找所有最短路徑。 我的想法是,在反轉圖形之后,最大路徑將變為最小,並且如果我們將其除以最小值,則所有邊緣權重都將為“正”(> = 1,因為我們是相乘而不是相加)。 但是,當我運行算法時(下面是我的Python代碼),它似乎不起作用,我想知道這是因為我的算法根本不起作用,還是因為我的代碼錯誤。

#construct G' = (V,dist) for our modified Floyd-Warshall algorithm
# edge weights are initially the inverse of w(u,v). They are then all divided
# by the minimum value to ensure all are >= 1
dist = {}
nxt = {}
minimum = float("inf")
for i in e:
    dist[i] = {}
    nxt[i] = {}
    for j in e[i]:
        dist[i][j] = 1/e[i][j]
        nxt[i][j] = j
        if dist[i][j] < minimum:
            minimum = dist[i][j]

for i in dist:
    for j in dist[i]:
        dist[i][j] /= minimum

# Perform Floyd-Warshall
for k in v:
    for i in v:
        for j in v:
            try:
                one = dist[i][j]
                two = dist[i][k]
                three = dist[k][j]
            except KeyError:
                continue

            if one > two * three:
                dist[i][j] = two * three
                nxt[i][j] = nxt[i][k]

# Find the shortest cycle using shortest paths
minimum = float("inf")
for i in v:
    for j in v:
        if i == j:
            continue
        try:
            one = dist[i][j]
            two = dist[j][i]
        except KeyError:
            continue

        if one * two < minimum:
            minimum = one * two
            pair = [i,j]

def Path(u,v):
    if nxt[u][v] == None:
        return []
    path = [u]
    while u != v:
        u = nxt[u][v]
        path.append(u)
    return path

# Format the cycle for output
p1 = Path(pair[0],pair[1])
p2 = Path(pair[1],pair[0])
p = p1 + p2[1:]
print(p)

# Find the total value of the cycle
value = 1
for i in range(len(p)-1):
    value *= e[p[i]][p[i+1]]

print('The above cycle has a %f%% weight.'  % ((value-1)*100))

我用圖形G =(V,E)測試了上面的示例,其中

V = {a,b,c,d}, and 
E = {
    (a,b): 1/0.00005718 * 0.9975, 
    (a,c): 1/0.03708270 * 0.9975,
    (a,d): 18590.00000016 * 0.9975, 
    (b,a): 0.00010711 * 0.9975,
    (b,c): 0.00386491 * 0.9975, 
    (c,a): 0.03700994 * 0.9975,
    (c,b): 1/18590.00000017 * 0.9975,
    (c,d): 688.30000000 * 0.9975,
    (d,a): 1/18590.00000017 * 0.9975,
    (d,c): 1/688.30000000 * 0.9975
}

上圖的輸出是周期[a,d,a]最好,權重為86.385309%。 但是,正如我們所看到的,周期[a,b,c,a]權重為148.286055%,這要好得多,這使我相信算法錯誤或在某處出錯。

任何建議深表感謝!

我認為問題不是實現,而是算法。 確實采用以下具有四個頂點a,b,c和d以及以下邊的示例:

W(A,B)= 10/3

瓦特(B,C)= 10

瓦特(C,d)= 5

瓦特(d,A)= 10/3

瓦特(d,B)= 5

然后,您的算法將返回有向循環(b,c,d,b),而最佳解決方案是(a,b,c,d,a)。

此外,您還應該知道問題可能是NP完全的,因為最長路徑問題是NP完全的(即使Shortest Path problem可以在多項式上解決),所以只有少數希望有一個如此簡單的算法為您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM