Grafalgo
Library of useful data structures and algorithms
/Users/jst/src/grafalgo/cpp/graphAlgorithms/sPath/spt.cpp
00001 // usage: spt method [src]
00002 //
00003 // Spt reads a graph from stdin, computes a shortest path tree (from src)
00004 // using the method specified by the argument and then prints the graph
00005 // and the spt. Src defaults to 1.
00006 //
00007 
00008 #include "stdinc.h"
00009 #include "Wdigraph.h"
00010 
00011 using namespace grafalgo;
00012 
00013 extern void dijkstra(Wdigraph&, vertex, vertex*, int*);
00014 extern void bfScan(Wdigraph&, vertex, vertex*, int*);
00015 
00016 int main(int argc, char *argv[]) {
00017         int s; Wdigraph dig; cin >> dig;
00018         
00019         s = 1;
00020         if (argc < 2 || argc > 3 ||
00021             (argc == 3 && sscanf(argv[2],"%d",&s) != 1))
00022                 Util::fatal("usage: spt method [src]");
00023 
00024         int *p = new vertex[dig.n()+1];
00025         int *d = new int[dig.n()+1];
00026 
00027         if (strcmp(argv[1],"dijkstra") == 0)
00028                 dijkstra(dig,s,p,d);
00029         else if (strcmp(argv[1],"bfScan") == 0)
00030                 bfScan(dig,s,p,d);
00031         else
00032                 Util::fatal("spt: undefined method");
00033 
00034         Wdigraph sptree(dig.n(),dig.n()-1);
00035         int sum = 0;
00036         for (vertex u = 1; u <= dig.n(); u++) {
00037                 if (p[u] != 0) {
00038                         edge e = sptree.join(p[u],u);
00039                         sptree.setLength(e,d[u]);
00040                         sum += (d[u] - d[p[u]]);
00041                 }
00042         }
00043         sptree.sortAdjLists();
00044         string s1;
00045         cout << dig.toString(s1) << endl;
00046         cout << sptree.toString(s1) << endl;
00047         cout << "total cost=" << sum << endl;
00048         delete [] p; delete [] d;
00049         exit(0);
00050 }
 All Classes Files Functions Variables Typedefs Friends