MIT6.006 ——lec11

110 阅读1分钟

Weighted graphs:

Different from the unweighted graph,the weighted graph's edge is weighted .

In the unweighted graph , we use the number of edge to represent the lengh of the path. Now,in the weighted graph,we map each edge to a real number to differ different edges.

In other words, different edge matters differently.

i.e.: In the social network, the positive edge between 2 people represents that they are in good relationship,samely the negative edge explains that they are enemies.

Relax:

We need to continually update the shortest distance from s to v.

def relax(u, v, parent, Adj, w, d):
    if d[v] > d[u] + w[u, v]:
        d[v] = d[u] + w[u, v]
        parent[v] = u

DAG relaxation:

Why DAG?;

if not a directed acyclic graph,it may exit a negative cycle,where the distance will consatantly dicrease to infinite.So we emphasize DAG

def relax(u, v, parent, Adj, w, d):
    if d[v] > d[u] + w[u, v]:
        d[v] = d[u] + w[u, v]
        parent[v] = u


def DAG_Relaxation(Adj, w, s):  # w:weight s: start
    _, order = dfs(Adj, s)
    order.reverse()
    d = [float('inf') for _ in Adj]  # initialize the distance function
    parent = [None for _ in Adj]
    d[s], parent[s] = 0, s
    for u in order:
        for v in Adj[u]:
            relax(u, v, parent, Adj, w, d)
    return d, parent