[英]How to find the sum weight of all edges reachable from some vertex?
Consider a directed graph with no cycles.
考虑没有周期的有向图。 I need to find for each
u
the total weight of edges reachable fromu
(by reachable we mean there's a path fromu
to somev
).我需要为每个
u
找到可从u
到达的边缘的总权重(通过可到达我们意味着存在从u
到v
的路径)。
Now, what I thought about is running topological sort and then starting to run from the last node to the first node (possible by interchanging the direction of the edges) 现在,我想到的是运行拓扑排序,然后开始从最后一个节点运行到第一个节点(可以通过交换边的方向来进行)
And then we're evaluating f[v] = f[u] + w(u,v)
. 然后我们评估
f[v] = f[u] + w(u,v)
。
but there's a problem; 但是有一个问题 for this graph, we will count
f[d]
twice. 对于此图,我们将计算
f[d]
两次。 How can I overcome this? 我该如何克服?
You can use either BFS or DFS to achieve this. 您可以使用BFS或DFS来实现此目的。
total = 0
dfs (node):
if visited[node] == 1:
return
visited[node] = 1
for all u connected to node:
total += weight[node][u]
dfs(u)
Note that we check the visited after total += weight[node][u]
. 请注意,我们在
total += weight[node][u]
之后检查total += weight[node][u]
。
You can use a bottom up approach. 您可以使用自下而上的方法。 that is firstly calculate the outdegree of each vertex, Now the vertices with 0 outdegree would have F[u] = 0 for them.
首先计算每个顶点的出度,现在出度为0的顶点的F [u] = 0。 Now add all such vertices in a queue Q.
现在,将所有这些顶点添加到队列Q中。
Also you would need to store the transpose of the Graph, suppose it was T. 同样,您需要存储图的转置,假设它是T。
While(!Q.empty){
u=Q.front();
Q.pop();
for all edges E originating from T[u]{
F[v]+=w; (where (u,v) was the edge with w as weight)
//now remove u from the graph
outdegree[v]--;
if(outdegree[v]==0)
Q.push(v);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.