Application of detailed diagrams (minimum spanning tree, topological sort, critical path, shortest path) _c language

Source: Internet
Author: User
Tags array definition joins

1. Minimum spanning tree: spanning tree with the smallest sum of weights in all spanning trees of a undirected connected graph

1.1 Problem Background:
If you want to establish a communication network between n cities, then connect N cities only need n-1 line. At this point, nature will consider the question of how to establish this communication network on the basis of the most economical cost. In each of the two cities can be set up a line, corresponding to pay a certain economic costs. n between cities, it is possible to set up n (n-1)/2 lines, so how to select n-1 strips in these possible lines to minimize the total cost?

1.2 Analysis of problems (model creation):

can use connected network to represent n cities and N cities may be set up communication lines, where the vertices of the network to represent the city, the edge of the two cities, the line, assigned to the edge of the weight of the corresponding price. For n-Vertex connected networks, many different spanning trees can be built, and each spanning tree can be a communication network. That is, the spanning tree of undirected connected graphs is not unique. The set of edges traversed by a connected graph and the set of all vertices in the graph constitute a spanning tree of the graph, and different spanning trees may be obtained for different traversal of connected graphs.

Figure G5 The spanning tree of undirected connected graphs is shown in (a), (b), and (c) diagrams:

G5

Three tree spanning trees in G5 :

It can be proved that the undirected connected graph with n vertices, regardless of the shape of the spanning tree, is available in all spanning trees and has only n-1 edges.

1.3 Definition of minimum spanning tree:

If a undirected connected graph is a net, then all of its spanning trees must have an edge of the weight of the smallest spanning tree, which we call the spanning tree as the smallest spanning tree, abbreviated as the minimum spanning tree.

The nature of the minimum spanning tree:
Assuming that n= (v,{E}) is a connected network, U is a non-empty set of the vertex set V, if (u,v) is an edge with a minimum weight (the cost), where

There must be a minimum spanning tree containing edges (u,v).

1.4 Solution:

Two common algorithms for constructing minimum spanning trees are: Primm (Prim) and Kruskal (Kruskal). They all use the nature of the minimum spanning tree

1. Primm (Prim) algorithm: Wired point, suitable for edge density. Time complexity O (n^2)

Suppose g= (v,e) is a connected graph, where V is the set of all vertices in the network diagram, E is the set of all the weighted edges in the network diagram. Set two new sets of U and T, where

The set U (vertex set) is used to store vertices in the smallest spanning tree of G.

The set T (the Edge set) holds the edges of the smallest spanning tree of G.

T, the initial state of U: the initial value of the set U is U={U1} (assuming that the minimum spanning tree is constructed from the vertex U1), the initial value of the set T is t={}.

The idea of the Prim algorithm is to select an edge (U,V) ∈e with a minimum weight from all u∈u,v∈v-u edges, add the vertex v to the set U, add the Edge (U,V) to the set T, and repeat until u=v, when the minimum spanning tree is constructed, and the set T Contains all the edges of the minimum spanning tree.

The Prim algorithm can be described in the following procedure, where Wuv represents the weights on the vertex u and vertex v edges.
(1) u={u1},t={};
(2) while (U≠V) do
(u,v) =min{wuv;u∈u,v∈v-u}
t=t+{(U,V)}
U=U+{V}
(3) End.
According to the prim method, starting from Vertex 1, the production process of the minimum spanning tree of the net is as follows:

In order to realize the prim algorithm, two auxiliary Closedge are set up to save the weights of the edges with the least weights in each vertex of the v-u of the set. There is a corresponding component closedge[i-1 in the secondary array for each vi∈ (V-U), which includes two domains:

typedef struct ARCNODE

{

int Adjvex; The Adjex field stores the vertices attached to the side in U
Vrtype lowcost; The Lowcost field stores the weights on that edge
}closedge[max_vertex_num];

Obviously:

When the initial state is U={v1} (U1 is the starting vertex), the smallest edge in the V-u, which is the edge of the attachment vertex v1, finds one of the lowest cost edges (u0,v0) = (1,3) for an edge on the build tree.
The V0 (=V3) is also incorporated into the set U. The value of the secondary array is then modified.

1) will closedge[2].lowcost = 0;//to represent vertex V3 Three has been merged into U

2) because the weight of the Edge (V2,V3) is less than closedge[1].lowcost, it is necessary to modify closedge[1] for the Edge (V2,V3) and its weight, the same modification closedge[4],closedge[5].

Closedge[1].adjvex = 3.

Closedge[1].lowcost = 5.

Closedge[4].adjvex = 1.

Closedge[4].lowcost = 5.

Closedge[5].adjvex = 3.

Closedge[5].lowcost = 6.

And so on, until u = V;

The following figure shows the process of constructing the minimum spanning tree of net figure 7.16 with the above algorithm:


Prim Algorithm implementation:

Follow the algorithmic framework:

(1) u={u1},t={};
(2) while (U≠V) do
(u,v) =min{wuv;u∈u,v∈v-u}
t=t+{(U,V)}
U=U+{V}
(3) End.
When the non-network uses the adjacency matrix storage of two-dimensional arrays, the C language of the Prim algorithm is:

Record the auxiliary array definition of the lowest cost side of the vertex set U to v-u: 
 //struct{ 
 //Vertextype Adjvex;//Vrtype lowcost 
 ; 
 //}closedge[Max_ Vertex_num] 
void Minispantree_prim (mgraph g,vertextype u) { 
///using the PRIMM algorithm to construct the minimum spanning tree T of the net G from the U vertex, and output the edges of the T. 
 k =locatevex (g,u); 
 for (j=0; j<g.vexnum; ++j) 
  if (j!=k) closedge[j] ={u, G.ARCS[K][J].ADJ};//{Adjvex, Lowcost} 
 closedge[k].lowcost = 0;//initial, u={u} for 
 (i=1;i<g.vexnum;++i) {//Select the remaining g.vexnum-1 vertex 
  k= Minimum (Closedge), 
  printf (Closedge[k].adjvex, g.vexs[k]);//output Spanning Tree's Edge 
  //k vertex is merged into U set 
  closedge[k]. lowcost=0; 
  For (j=0 j<g.vexnum; ++j) 
   if (g.acrs[k][j].adj<closedge[j].lowcost) closedge[j]={g.vexs[k],g.arcs[k][j] . adj}; 
 } For 
}//minispantree 

Assuming that there are n vertices in the net, the frequency of the first circular statement to initialize is N, and the second loop statement has a frequency of n-1. There are two internal loops: one is to find the minimum value in the Closedge[v].lowcost, its frequency is n-1, and the second is to select the edge with the lowest cost, the frequency is N. Thus, the time complexity of the PRIMM algorithm is O (N2), which is independent of the number of edges in the net, so it is suitable for the minimum spanning tree of the dense net.
2. Kruskal (Kruskal): From point to line, suitable for edge sparse nets. Time complexity: O (E * loge)

Kruskal algorithm is a method of constructing the minimum spanning tree in order to increase the weights of the edges in the net.

The basic idea is:

1) Set the undirected connected network as g= (v,e), so that the minimum spanning tree of G is T, its initial state is t= (v,{}), that is, the minimum spanning tree T is composed of n vertices in Fig g, and there is no edge between the vertices, so that each vertex in T is composed of a connected component.

2 Select the least expensive edge in E, and if the vertex attached to it falls in a different connected component of T, the Edge is added to T, otherwise the edge is discarded and the next edge is selected (if the two vertices attached to the edge belong to the same connected component, the edge is dropped so as not to cause the loop). Thus, when the number of connected components in T is 1 o'clock, the connected component is a minimum spanning tree of G.

The process of constructing a minimum spanning tree in accordance with the Kruskal method is shown in the figure:

In the process of construction, according to the order of the weights of the edges in the net from small to large, the edges that are currently not selected are selected with the least value of the edge set. According to the concept of spanning tree, the spanning tree of n nodes has n-1 edges, so the process is repeated until the n-1 edge is selected, which constitutes a minimal spanning tree.


implementation of Kruskal algorithm:
the framework of the algorithm:

Constructing non-connected graph t= (v,{})

K = i= 0;//k as the number of sides

while (K < n-1) {

i++;

Check the weight of section I on side E

Minimum Edge (U,V)

If the (u,v) join T is not the T-generating loop,

Then (u,v) joins T, and k++

}

C Language implementation:

C language implementation of the Kruskal algorithm, where the function find is to look for the vertex in the graph of the tree root node in the array father ordinal number. It should be explained that the data type of the vertex is defined as integral type in the program, and in practical application, it can be set according to the actual need.

typedef int ELEMTYPE; 
typedef struct { 
Elemtype v1; 
Elemtype v2; 
int cost; 
} Edgetype; 
void Kruskal (Edgetype edges[],int N)/ 
* The minimum spanning tree of a graph Kruskal with n vertices is constructed with the edges method/ 
{int Father[maxedge]; 
int i,j,vf1,vf2; 
for (i=0;i<n;i++) father[i]=-1; 
i=0;j=0; 
while (I<maxedge && j<n-1) 
{vf1=find (FATHER,EDGES[I].V1); 
Vf2=find (FATHER,EDGES[I].V2); 
if (VF1!=VF2) 
{father[vf2]=vf1; 
j + +; 
printf ("%3d%3d\n", edges[i].v1,edges[i].v2); 
} 
i++ 
} 
} 
 
find function 
int finding (int father[],int v)/ 
* Looking for the root node of the tree where Vertex v is located/ 
{int t; 
T=v; 
while (father[t]>=0) 
t=father[t]; 
return (t); 
} 
 

2. AoV Network and Topology ordering: The topology ordering is ordered by the order of the partial order. Build the model is AOV net
2.1. AoV Network (activity on vertex Network)

All works or processes can be divided into small projects or stages, which are called activities. If an activity is represented by a vertex in a graph, and a forward edge (ARC) represents a priority relationship between activities, then the forward graph of such activity at the vertex is called the AOV Network (the active on Vertex network). In the AoV net, if there is a direction path between vertex I to Vertex J, the vertex i is the precursor of Vertex J, or Vertex J is the successor of vertex I. If <i,j> is an arc in the graph, the vertex i is the direct precursor of Vertex J, and Vertex J is the direct back drive of vertex i.

The arcs in the AOV network represent the constraints between activities. For example, students majoring in computer science must complete a set of basic courses and specialized courses to graduate. In what order do students study these courses? This problem can be seen as a big project, and its activity is to learn every course. The names of these courses and the corresponding codes are shown in the table.

Priority diagram between courses:


The topological order series of the graph:

Attention:
There should not be a direction ring in the aov-network, because the existence of the loop means that an activity should be a prerequisite for itself. If such a flow chart is designed, the project will not be carried out. But for the program Data flow diagram, it indicates that there is a dead loop. Therefore, for a given aov-network should first determine whether there is a ring in the network. The method of detection is to construct the topological ordered sequence of the vertex of the direction graph, if all vertices in the net are in its topological ordered sequence, then there must be no ring in the aov-network.

2.2. Topology sorting

Basic knowledge of discrete Mathematics:

First, we review the two concepts of partial order set and total order set in discrete mathematics.

If the two-yuan relationship in set A is reflexive, asymmetric, and transitive, R is a partial order relationship on a. Set A is called a partial order set together with relation R.

If R is a partial order relation on a set a, if ARB or bra are required for each a, b∈a, then R is the full order relationship on a. Set A is called a full order set together with relation R.

Intuitively, the partial order refers to only some members of the set can be compared, and the whole sequence refers to all members of the set can be compared.
[For example], in Figure 7.25, the two forward graphs, in which arcs (x,y) represent X≤y, (a) represent a partial order, and (b) represent a full order. If a v2≤v3 arc (symbol "≤") is artificially added to the graph on (a) to indicate that the V2 is ahead of the V3), then (a) is also a full order, and this whole order is called topological order (topological orders), and the topological order is ordered by the ordering of the partial order.


2.3 Topology sorting algorithm

The methods and steps for AOV network topology sequencing are:
1. Select a vertex without a precursor from the AOV network (the entry of the vertex is 0) and output it;
2. Delete the vertex from the net and delete all the forward edges issued from the vertex;
3, repeat the above two steps, until the remaining network no longer exist without the vertex of the predecessor.

There are two kinds of results: one is that all the vertices in the net are output, which means there is no forward loop in the net, and the other is that the vertex in the net is not all output, and the remaining vertices are not the apex, which indicates that there is a direction loop in the net.

For example, in the diagram shown in (a) below, V1, and V6 have no precursors, and are optional. Assuming that the first output V6, after the deletion of V6 and arc <v6,v4>,<v6,v5>, only vertex v1 no precursor, then output VL and delete VL and Arc <v1,v2>, <v1,v3> and <v1, V4> After that, V3 and V4 had no precursors. And so on, you can choose one from the other to continue. Finally, the topological order sequence of the direction graph is:

v6-v1-v4-v3-v2-v5


Graph aov-Network and the process of its topological ordered sequence generation
(a) aov-net; (b) After the output V6, (c) after the output V1, (d) after the output V4; (e) after the output V3; (f) after the output v2
In order to realize the above algorithm, the adjacency table is used to store the AOV network, and a data field with the vertex entry in the vertex node of the adjacency table is added, that is, the apex structure is set as:

The description of the node structure of the vertex table is changed to:
typedef struct vnode{/* Vertex table node * *
int count/* Store vertex entry
Vertextype Vertex; /* Vertex Domain * *
Edgenode * Firstedge; /* Side Table head pointer * *
}vertexnode;
of course, you can also set up a one-dimensional array to store the entry of each node without adding an entry field. the algorithm can be set up a stack, the general network in the degree of 0 of the vertices are put into the stack. To do this, the algorithm steps for topological sorting are:
1, will not have the predecessor Vertex (count field is 0) presses into the stack;
2, from the stack to exit the top element output, and the vertex out of all the direction of the edge to delete, that is, the entry of its adjacent vertices minus 1;
3, the new entry degree of 0 of the vertex back into the stack;
4, repeat ②~④ until the stack is empty. Either all vertices have been output at this point, or vertices with 0 in the remaining vertices are not present.

To avoid repeated detection of vertices with zero entry, you can set up a stack to hold all vertices with zero degrees.

The Status topological Sort (Algraph g) { 
//forward graph G uses an adjacency table storage structure. 
//If G has no loop, then output 1 topological sequences of vertices of G and return OK, otherwise error. 
 Findindegree (G,indegree)//For each vertex indegree[0..vernum-1] 
 Initstack (s); 
 for (i=0;i<g.vexnum; ++i) 
 if (!indegree[i) Push (s,i)//build 0 into the vertex stack, S into 0 of the stack 
 count=0; Count while (!) on the output vertex 
 . Stackempty (S)) { 
  Pop (s,i); 
  printf (i,g.vertices[i].data); ++count;//Output I vertex and count for 
  (p=g.vertices[i). Firstarc;p p=p->nextarc) { 
   k=p->adivex;//reduction in the entry of each adjacency point of vertex 1 
   if (! (--indegree[k]) Push (S,K)//If the entry is reduced to 0, then the stack 
  }//for 
 }//while 
 if (count<g.vexnum) return ERROR;//The graph has a loop 
 else return OK; 

3. Critical Path (AOE network): in the aoe-network some activities can be carried out in parallel, so the shortest time to complete the project is from the start point to the completion point of the longest path length, path length of the longest path is called the critical Path (Critical path).

3.1AOE Net: (Activity on edge Network)
AOE network schematic diagram if in the weighted direction graph, the vertex to represent the event, with a direction to the edge of the activity, the edge of the value of the activity (such as the duration of the activity), then the right to the graph called the AOE network.

3.2 Practical Questions:

If you use the AOE net to represent a project, it is not enough, then, to consider the priority relationships between the various projects, more to care about the minimum time of completion of the project, and which activities will affect the progress of the whole project, and whether the acceleration of these activities will increase the efficiency of the whole project. Therefore, the activities required to complete the scheduled project are usually listed in the AOE network. The time that each activity is scheduled to be completed, what events to take place, and the relationship between these events and activities, can determine whether the project is feasible, estimate the time of completion of the project, and determine which activities are critical to the progress of the project.

The figure is a hypothetical aoe-network with 11 activities:

There are 9 events v1,v2,v3,...,v9, each of which indicates that the activity before it has been completed, and that the activity after it can begin. If V1 says the whole project begins, V9 says the whole project is over, V5 says A4 and A5 have been completed, A7 and A8 can start. The number associated with each activity is the time that is required to perform the activity. For example, the activity A1 need 6 days, A2 need 4 days and so on.

Unlike the aov-network, the problems to be studied in the aoe-network are:
(1) How long does it take at least to complete the whole project?
(2) Which activities are the key factors affecting the progress of the project?

3.3 Critical paths

Because some activities in the aoe-network can be carried out in parallel, the shortest time to complete the project is the length of the longest path from the start point to the completion point (the path length is the sum of the duration of each activity on the path, not the number of arcs on the path). The path with the longest path length is called the Critical path (Critical path).

AOE Network-related concepts:
1 path length: The sum of the duration of each activity on the path

2 The shortest time to complete the project: as the AOE network activities are carried out in parallel, so the shortest time to complete the project is from the start point to the completion point of the longest length of strength.
3 Activity earliest start (earlist time) (E (i)): The longest path from the start point to the Vertex VI is called the earliest occurrence time of event VI. This time determines the earliest start time of the activity represented by the arc at the end of VI.
4 activity Late Start (latest time) (L (i)): The latest start of the activity without delaying the completion of the whole project
5 The time margin of the activity: The latest start time of the activity minus the earliest start time
6 Critical Path (critical path): The path with the longest path length is called the critical path
7 Key activities (critical activity): Activities on the critical path are called key activities, and the key activities are characterized by: E (i) =l (i) The purpose of the analysis of critical paths is to identify the key activities throughout the project in order to improve the efficiency of key activities and shorten the duration of the entire project.
3.4 Solution:
From the above analysis, the identification of key activities is to find E (i) =l (i) activities. In order to obtain the active E (i) and L (i) of the aoe-net, the earliest occurrence time of the event ve (j) and the latest time VL (j) are first obtained. If the active AI is represented by Arc <j,k>, its duration is Dut (<j,k>), the following relationships are:

E (i) = ve (j)

L (i) = VL (k)-dut (<j,k>)

ve (j) and VL (j) need to be carried out in two steps:
(1) Starting from VE (0) forward recursion

Wherein, T is the Union of all arcs with the first J Vertex as the head.
(2) Backward recursion from VL (n-1) =ve (n-1)

where S is the set of all arcs with the end of vertex i.

The calculation of these two recursive formulas must be carried out under the precondition of topological order and inverse topological order respectively. that is, ve (j-1) must be determined at the earliest possible time for all precursors of VJ, and VL (J-1) must be determined at the latest date of all subsequent VJ. Therefore, you can compute VE (j-1) and VL (J-1) on the basis of topological ordering.

3.5 Algorithms for critical paths:
(1) Inputting e-Arc <j,k>, establishing the storage structure of aoe-network;
(2) from the source point V0, so that ve[0]=0, according to the topological order of the remaining vertices of the earliest occurrence time ve[i] (1≤i≤n-1). If the number of vertices in the topological ordered sequence is less than that in the net, then there is a ring in the net, the critical path cannot be obtained, and the algorithm terminates. Otherwise, the execution step (3).
(3) from the meeting point VN, make vl[n-1]=ve[n-1], according to the inverse topological order of the rest of the vertices of the latest occurrence time Vl[i] (n-2≥i≥0);
(4) According to the VE and VL values of each vertex, we find the earliest start time E (s) and the late Start time L (s) of each arc s. If an arc satisfies the condition E (s) =l (s), it is a critical activity.

First topology sorting algorithm: Topologicalorder ()

Criticalpath is the algorithm for finding the critical path:

Status Topologicalorder (algraph g,stack &t) {//have to network G uses adjacency table storage structure to find the earliest occurrence time ve (global variable) of each vertex event. T is a topological sequence vertex stack, S is a 0-degree vertex stack. 
 If G has no loop, return a topological sequence of g, function value is OK, otherwise error. Findindegree (G,indegree);//For each vertex indegree[0..vernum-1] for (i=0;i<g.vexnum; ++i) if (!indegree[i)) Push (s,i)// Build 0 into the vertex stack, s into the 0 into the stack initstack (T); count=0;ve[0..g.vexnum-1]=0;//Initialize while (! 
  Stackempty (S)) {//j vertex into T stack and Count POPs (S,J); Push (t,j); ++count; for (P=G.VERTICES[J].FIRSTARC;P;P=P-&GT;NEXTARC) {k=p->adjvex;//the degree of entry for each adjacency point of the I vertex minus l if (--indegree[k]==0) Push (s,k) ;//If the entry is reduced to 0, then the stack if (ve[j]+* (P->info) >ve[k]) ve[k]=ve[j]+* (p->info);}//for * (P->info) =dut (<j,k> }//while if (count<g.vexnum) return ERROR;//The Net has loop else return OK;}//topologicalorder Status Cr 
 Iticalpath (Algraph g) {//g is a forward network, output g of the key activities. if (! Stackempty (t)) for (POPs (T, j), P=g.vertices[j].firstarc;p p=P-&GT;NEXTARC) {k=p->adjvex; dut=* (p->info);//dut<i,k> if (vl[k]-dut<vl[j)) Vl[j]=vl[k]-dut;}//fo R for (J=0;J&LT;G.VEXNUM;++J)//Ee,el and critical activity for (P=G.VERTICES[J];P;P=P-&GT;NEXTARC) {k=p->adjvex; dut=* (p->in FO); Ee=ve[j];el=v1[k]-dut;tag = (ee==e1)?  ' * ': '; printf (j,k,dut,ee,el,tag);//Output Key activity}}//criticalpath

Figure (a) the critical path of the network: visible A2, A5, and A7 are key activities that form a critical path from the source point to the meeting point, as shown in figure (b).

Figure (a) the calculated result of the net shown in:

4. Shortest path: The Shortest path problem is a classical algorithm problem in graph research, which aims at finding the shortest path between two nodes in a graph (composed of nodes and paths).
The shortest path problem is another typical application problem of graphs. For example, a road network in a certain region, given the distance between the N cities within the network and the connecting roads between the cities, can find an example of the nearest route between City A and city B?


If the city with a point, the city between the highway with the side, the length of the road as the weight of the edge, then, this problem can be attributed to the network map, to find a point B in all the paths, the edge of the right value and the shortest path. This path is the shortest path between two points, and the first vertex on the path is the source (sourse) and the last vertex is the end point (destination).

The shortest path problem of Single-source point: Given a weighted g= (v,e) and source point v∈v, the shortest path of the remaining vertices from V to G is obtained. In the following discussion, assume that the source point is v0.

Dijkstra algorithm for solving problems:

That is, an algorithm of Dijkstra (Dijkstra) to produce shortest path in order of increasing path length. First, a shortest path of shortest length is obtained, and then a shortest path with short length is obtained by reference to it, and so on, until all the shortest paths from Vertex v to other vertices are obtained.

The basic idea of the algorithm is:

Sets S and t=v-s of two vertices, set S holds vertices that have found the shortest path, and the set T holds vertices of the shortest path that are not currently found.

In the initial state, the set S contains only the source point V0, then, from the set T, the vertex v0 with the shortest path length is added to the set S, and the set S, each adding a new vertex u, modifies the shortest path length value of the vertex v0 to the remaining vertices in the set T, and sets T The new shortest path length value of each vertex is the original shortest path length value and the shortest path length value of the vertex u plus the smaller value in the path length value of U to the vertex. This process repeats until the vertices of the set T are all added to S.

Implementation of Dijkstra algorithm:

First, the introduction of an auxiliary vector D, each of its components d[i] represents the length of the shortest path currently found from the point V to each endpoint VI. Its initial state is: if the arc from V to VI, then d[i] is the right value on the arc, otherwise the d[i] is ∞. Obviously, the length is:

D[j]=min{d[i]| Vi∈v}
Path is a shortest path from the shortest length from V. This path is (V, VJ).

So, which is the shortest length of the next short time? Assuming that the end point of the short path is VK, it is conceivable that the path is either (V, VK), or (V, VJ, VK). Its length is either the weight of the arc from V to VK, or the sum of the weights of D[j] and arcs from VJ to VK.

According to the idea of the algorithm described earlier, in general, the length of the shortest path with a short length of the next one must be:
D[j]=min{d[i]| Vi∈v-s}
Wherein, d[i] or the weights on the arc (V, vi), or the sum of weights on the d[k] (Vk∈s and arcs (VK, VI).

Based on the above analysis, the following algorithms can be obtained:
(1) Assuming the weighted adjacency matrix edges to represent the weighted direction graph, Edges[i][j] represents the arc 〈vi, the weight value on the vj〉. If 〈vi, vj〉 does not exist, the edges[i][j] is ∞ (the maximum allowable value can be substituted on the computer). S is a collection of endpoints that have found the shortest path from V, and its initial state is the empty set. Then, starting from V to the rest of the vertices (endpoints) VI may achieve the initial value of the shortest path length:
d[i]= edges[locate vex (g,v)][i] Vi∈v
(2) Select VJ to make
D[j]=min{d[i]| Vi∈v-s}
VJ is the end point of the shortest path from V that is currently being evaluated. Make
S=S∪{J}
(3) Modify the shortest path length from V to set V-s to the VK vertex. If
d[j]+ Edges[j][k]<d[k]
Then modify D[k] to
d[k]=d[j]+ Edges[j][k]
Repeat operation (2), (3) a total of n-1 times. The shortest path of the remaining vertices from V to graph is derived from the sequence of path length increment.

As shown in Figure 8.26, a weighted adjacency matrix for a G8 graph is:


The weighted adjacency matrix in the G8 of a forward network graph

The Dijkstra algorithm described in C language:

 void Shortestpath_dij (mgraph g,int v0,pathmatrix &p,shortpathtable &D) {//Dijk 
 The shortest path p[v of the V0 vertex to the remaining vertex V of the stra algorithm is obtained and its weighted length d[v]. 
 If P[V][W] is true, then W is the vertex on the shortest path from V0 to V. 
  FINAL[V] is true if and only if v∈s, that is, the shortest path from V0 to V has been obtained. For (v=0, v<g.vexnum; ++v) {final[v]=false; d[v]=g.arcs[v0][v]; for (w=0; w<g.vexnum; ++w) p[v][w] = false;//Set Empty Path if (d[v]<infinity) {p[v][v0]=true; P[v][v]=true}}//for D[v0] = 0; Final[v0] = TRUE;//Initialize, V0 vertex belongs to s set//Open 
  The primary loop, each time the shortest path to a v0 to a V vertex is obtained, and the V to S set is added. for (I=1 i<g.vexnum;++i) {//The rest of the g.vexnum-1 vertex min = INFINITY;//The closest distance known to the V0 Vertex for (w=0;w<g.vexnum;++w) if (!f INAL[W])//w vertex in V-s if (d[w]<min) {v=w;min=d[w];//w Vertex is closer to v0 vertex final[v]=true;///nearest to V0 Vertex joins S set for (w=0;w<g.ve XNUM;++W)//update current shortest path and distance if (!final[w]&& (Min+g.arcs[v][w]<d[w])) {//modify D[W] and P[w] D[w]=min+g.arcs[v][w];p[w ]=P[V]; P[w][w]=true//p[w]=p[v]+[w]}//if}//for}//shortestpath_dij 

The above is the application of all details of the diagram, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.