离散数学第十章 编程作业

虫虫的最短通路

求最短路可以用 SPFA 求,在 Python 下相对好写一点

找通路的话只要顺着 dis[] 找就可以了

n, m, s, t = map(int, input().split())
G = [[] for i in range (n + 1)]
dis = [2147483647 for i in range(n + 1)]
vis = [0 for i in range (n + 1)]
que = [0 for i in range (n * 10)]
l, r = 1, 0

for i in range (m):
    u, v, w = map(int, input().split())
    G[u].append((v, w))
    G[v].append((u, w))

dis[t] = 0 
r = r + 1
que[r] = t
while l <= r:
    x = que[l]
    l = l + 1
    vis[x] = 0
    for (u, w) in G[x]:
        if dis[u] > dis[x] + w:
            dis[u] = dis[x] + w
            if vis[u] == 0:
                vis[u] = 1
                r = r + 1
                que[r] = u

print(s, end=" ")
x = s
while x != t:
    for (u, w) in G[x]:
        if dis[u] + w == dis[x]:
            tmp = u
    x = tmp
    print(x, end=" ")
print("")
print(dis[s])

朱憨憨走在关键通路上

\(TE\)\(TL\) 都可以拓扑排序求

求关键路径的时候写成一个深搜

n, m, s, t = map(int, input().split())
G = [[] for i in range(n + 1)]
E = [[] for i in range(n + 1)]
TE = [0 for i in range(n + 1)]
TL = [2147483647 for i in range(n + 1)]
TL[0] = 0
In = [0 for i in range(n + 1)]
Out = [0 for i in range(n + 1)]
que = [0 for i in range(n + 1)]
head, tail = 1, 0

ans = []
tmp = [0 for i in range(n + 1)]
tmp[0] = s
def DFS(x, dep = 1):
    if x == t:
        tt = []
        for i in range(dep):
            tt.append(tmp[i])
        ans.append(tt)
        return
    for (u, w) in G[x]:
        if TE[u] == TL[u] and TE[u] == TE[x] + w:
            tmp[dep] = u
            DFS(u, dep + 1)

for i in range(m):
    u, v, w = map(int, input().split())
    G[u].append((v, w))
    In[v] = In[v] + 1
    E[v].append((u, w))
    Out[u] = Out[u] + 1

head, tail = 1, 1
que[1] = s

while head <= tail:
    x = que[head]
    head = head + 1
    for (u, w) in G[x]:
        if TE[u] < TE[x] + w:
            TE[u] = TE[x] + w
        In[u] = In[u] - 1
        if In[u] == 0:
            tail = tail + 1
            que[tail] = u

head, tail = 1, 1
que[1] = t
TL[t] = TE[t]

while head <= tail:
    x = que[head]
    head = head + 1
    for (u, w) in E[x]:
        if TL[u] > TL[x] - w:
            TL[u] = TL[x] - w
        Out[u] = Out[u] - 1
        if Out[u] == 0:
            tail = tail + 1
            que[tail] = u

DFS(s)

print("Dis=%d" % (TE[t]))    
for i in range(1, n + 1):
    print("Node",i, end="")
    print(": TE= %3d" % (TE[i]), sep="", end=" ")
    print(" TL= %3d" % (TL[i]), sep="", end=" ")
    print(" TL-TE= ", TL[i] - TE[i], sep="")

print(sorted(ans, key=len))
posted @ 2020-11-26 09:00  Withinlover  阅读(237)  评论(0编辑  收藏  举报