Week11-Chap5-Graph-Algorithms Sum Path On Tree
Week11-Chap5-Graph-Algorithms Sum Path On Tree
APPLIED ALGORITHMS
DEPTH FIRST SEARCH (DFS) AND APPLICATIONS
3
CONTENTS
4
THE LONGEST PATH ON THE TREE
• Given a tree T = (V, E), each edge (u,v) has weight w(u,v). Find the path with the
longest length on T (the length of the path is the sum of weight on all edges of the
path).
• Denote A[v] is the set of vertices adjacent to vertex v on T
• The algorithm is based on depth-first-search (DFS)
• Choose an arbitrary vertex s on T
• Perform DFS(s) to find vertex x farthest from s
• Perform DFS(x) to find the vertex y that is farthest from x
• The path from x to y found will be the longest path on T
5
THE LONGEST PATH ON THE TREE
6
THE LONGEST PATH ON THE TREE
7
TOTAL PATH LENGTH ON THE TREE
• Given a tree T = (V, E), each edge (u,v) has weight w(u,v). Vertex set V includes n vertices.
• Denote:
• A[v]: is the set of vertices adjacent to vertex v on T
• c(u,v) is the length of the unique path between two vertices u and v on T
• f(u): total path length from other vertices to u on T: f(u) = σ𝑣𝑉 𝑐(𝑣, 𝑢)
• Find f(u) for every u V
8
TOTAL PATH LENGTH ON THE TREE
9
TOTAL PATH LENGTH ON THE TREE
10
TOTAL PATH LENGTH ON THE TREE
11
TOTAL PATH LENGTH ON THE TREE
DFS1(u){ DFS2(u){
for v in A[u] do { for v in A[u] do {
if p(v) = 0 then { if p(v) = 0 then {
p(v) = u; F = f(u) – (d(v) + N(v)*w(u,v));
DFS1(v); f(v) = F + d(v) + w(u,v)*(n – N(v));
d(u) = d(u) + d(v) + N(v)*w(u,v); p(v) = u; DFS2(v);
N(u) = N(u) + N(v); }
} }
} }
} Phase2(){
Phase1(){ for v in V do { p(v) = 0; }
for v in V do { f(1) = d(1); p(1) = 1; DFS2(1);
p(v) = 0; d(v) = 0; N(v) = 1; f(v) = 0; }
} Main(){
p(1) = 1; DFS1(1); Phase1(); Phase2();
} }
12
TOTAL PATH LENGTH ON THE TREE
13
THANK YOU !
14