_all_pairs.c
上传用户:gzelex
上传日期:2007-01-07
资源大小:707k
文件大小:2k
开发平台:

MultiPlatform

  1. /*******************************************************************************
  2. +
  3. +  LEDA-R  3.2.3
  4. +
  5. +  _all_pairs.c
  6. +
  7. +  Copyright (c) 1995  by  Max-Planck-Institut fuer Informatik
  8. +  Im Stadtwald, 66123 Saarbruecken, Germany     
  9. +  All rights reserved.
  10. *******************************************************************************/
  11. /*******************************************************************************
  12. *                                                                              *
  13. *  ALL PAIRS SHORTEST PATHS                                                    *
  14. *                                                                              *
  15. *******************************************************************************/
  16. #include <LEDA/graph_alg.h>
  17. bool ALL_PAIRS_SHORTEST_PATHS(graph&G, const edge_array<num_type>& cost, 
  18.                                              node_matrix<num_type>& DIST)
  19.   // computes for every node pair (v,w) DIST(v,w) = cost of the least cost
  20.   // path from v to w, the single source shortest paths algorithms BELLMAN_FORD
  21.   // and DIJKSTRA are used as subroutines. Returns false if there is a
  22.   // negative cost circle and true otherwise.
  23.   edge e;
  24.   node v,w;
  25.   num_type C = 0;
  26.   forall_edges(e,G)  C += ((cost[e]>0) ? cost[e] : -cost[e]);
  27.   node s = G.new_node();
  28.   forall_nodes(v,G) G.new_edge(s,v);
  29.   edge_array<num_type> cost1(G);
  30.   node_array<num_type> dist1(G);
  31.   node_array<edge>  pred(G);
  32.   forall_edges(e,G)  
  33.     if (source(e)==s) cost1[e] = C;
  34.     else cost1[e] =  cost[e];
  35.   if (!BELLMAN_FORD(G,s,cost1,dist1,pred)) return false;
  36.   G.del_node(s);
  37.   forall_edges(e,G) cost1[e] = dist1[source(e)] + cost[e] - dist1[target(e)];
  38.   // (G,cost1) is a non-negative network
  39.   // for every node v compute row DIST[v] of the distance matrix  DIST 
  40.   // by a call of DIJKSTRA(G,v,cost1,DIST[v])
  41.   forall_nodes(v,G) DIJKSTRA(G,v,cost1,DIST[v],pred);
  42.   // correct the entries of DIST
  43.   forall_nodes(v,G)
  44.   { num_type dv = dist1[v];
  45.     forall_nodes(w,G) DIST(v,w) += (dist1[w] - dv);
  46.    }
  47.  return true;
  48. }