Algorithm Unit 4
Algorithm Unit 4
1
Multistage Graphs
2
(Four-stage graph corresponding to a three-project problem)
3
4
1 void FGraph(graph G, int k, int n, int p[])
2 // The input in a k-stage graph G = (V, E) with n
3 //vertices indexed in order of stages. E is a set
4 //of edges and c[i,j] is the cost of <i,j>.
5 // p[l:k] is a minimum-cost path.
6 {
7 float cost[MAXSIZE]; int d[MAXSIZE], r;
8 cost[n] = 0.0;
9 for (int j=n – 1; j>=1; j--) {// Compute cost[j].
10 let r be a vertex such that <j,r> is an edge
11 of G and c[j][r] + cost[r] is minimum;
12 cost[j] = c[j][r] + cost[r]
13 d[j] = r;
14 }
15 // Find a minimum-cost path.
16 p[l]=1; p[k] = n;
17 for( j =2; j <= k-1; j++) p[j] = d[p[j-1]];
18 }
5
6
(Graph with negative cycle)
14 }
7
(Directed graph and associated matrices)
8
(Directed graph with a negative-length edge)
9
(Shortest paths with negative edge lengths)
The pseudocode of the following program computes the length of the shortest path
from vertex v to each other vertex of the graph. This algorithm is referred to as the
Bellman and Ford algorithm.
11
12
Algorithm for 0/1 Knapsack Problem:
struct PW {float p, w; };
1 void DKnap (float p[], float w[], int x, int n, float m)
2 {
3 struct PW pair[SIZE]; int b[MAXSIZE], next;
4 b[0]=1; pair[l].p = pair[l].w =0.0; //S0
5 int t=l; h=1; // Start and end of S0
6 b[l] = next = 2; // Next free spot in pair[]
7 for (int i =1; i<=n-1; i++) {// Generate Si.
8 int k=t;
9 int u = Largest(pair, w, t, h, i, m);
10 for (int j =t ; j<=u; j++) { // Generate S1i-1 and merge.
11 float pp = pair[j].p + p[i]; float ww =pair[j].w + w[i];
12 // (pp,ww) is the next element in S1i-1.
13 while((k <= h) && (pair[k].w <= ww)) {
14 pair[next].p = pair[k].p; pair[next].w = pair[k].w;
13
15 next++; k++;
16 }
17 if ((k<= h) && ((pair[k].w ==ww)) {
18 if( pp < pair[k].p) pp =pair[k].p; k++;
19 }
20 if ( pp > pair[next - l].p) {
21 pair[next].p=pp; pair[next].w = ww; next++;
22 }
23 while ((k <= h) && (pair[k].p<= pair[nex - l].p))
24 k++;
25 }
26 // Merge in remaining terms from Si-1
27 while (k <= h) {
28 pair[next].p = pair[k].p; pair[next].w:=pair[k].w;
29 next++; k ++;
30 }
31 // Initialize for Si+1.
32 t = h + 1; h =next - 1;b[i + 1] = next;
33 }
34 TraceBack(p, w, pair, x, m, n);
35 }
14
The Travelling salesperson Problem
15
(Directed graph and edge length matrix c)
16
17