CHAPTER 25 Weighted Graphs and Applications Objectives ⢠To ...
CHAPTER 25 Weighted Graphs and Applications Objectives ⢠To ...
CHAPTER 25 Weighted Graphs and Applications Objectives ⢠To ...
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
131 for (int i = 0; i < getSize(); i++)<br />
132 {<br />
133 if (find(T.begin(), T.end(), i)== T.end()<br />
134 && cost[i] < currentMinCost)<br />
135 {<br />
136 currentMinCost = cost[i];<br />
137 u = i;<br />
138 }<br />
139 }<br />
140<br />
141 T.push_back(u); // Add a new vertex to T<br />
142 totalWeight += cost[u]; // Add cost[u] to the tree<br />
143<br />
144 // Adjust cost[v] for v that is adjacent to u <strong>and</strong> v in V - T<br />
145 for (Edge* e: neighbors[u])<br />
146 {<br />
147 if (find(T.begin(), T.end(), e->v) == T.end()<br />
148 && cost[e->v] > static_cast(e)->weight)<br />
149 {<br />
150 cost[e->v] = static_cast(e)->weight;<br />
151 parent[e->v] = u;<br />
152 }<br />
153 }<br />
154 } // End of while<br />
155<br />
156 return MST(startingVertex, parent, T, totalWeight);<br />
157 }<br />
158<br />
159 template<br />
160 ShortestPathTree <strong>Weighted</strong>Graph::getShortestPath(int<br />
sourceVertex)<br />
161 {<br />
162 // T stores the vertices whose path found so far<br />
163 vector T;<br />
164<br />
165 // parent[v] stores the previous vertex of v in the path<br />
166 vector parent(getSize());<br />
167 parent[sourceVertex] = -1; // The parent of source is set to -1<br />
168<br />
169 // cost[v] stores the cost of the path from v to the source<br />
170 vector cost(getSize());<br />
171 for (unsigned i = 0; i < cost.size(); i++)<br />
172 {<br />
173 cost[i] = INFINITY; // Initial cost set to infinity<br />
174 }<br />
175 cost[sourceVertex] = 0; // Cost of source is 0<br />
176<br />
177 // Exp<strong>and</strong> T<br />
178 while (T.size() < getSize())<br />
179 {<br />
180 // Find smallest cost v in V - T<br />
181 int u = -1; // Vertex to be determined<br />
182 double currentMinCost = INFINITY;<br />
183 for (int i = 0; i < getSize(); i++)<br />
184 {<br />
185 if (find(T.begin(), T.end(), i)== T.end()<br />
186 && cost[i] < currentMinCost)<br />
187 {<br />
188 currentMinCost = cost[i];<br />
10