0

I need to read in a file and build a directed graph from it. I am working in C++. The file looks like this:

SFA SLC 700  59
SFO LV  420  39 
LAX LV  231  23 
LV  SLC 362  29 
LAX SFO 344  39 
LAX SLC 581  57 
SFA SFO 679  67 
SFO SLC 605  19 
PHX DEN 586  65 
LV  PHX 256  21 
DEN SFA 1026 72 
DEN LAX 844  69 
SLC DEN 379  49 
SLC SJC 585  29 
SJC SFO 51   19

The first line means there is a flight from SFA to SLC which is 700 miles and cost $59 and each line follows this formula. I am having a really hard time figuring out a good way to do this. Any help would be so much appreciated. Thank you in advance.

M. Meacham
  • 121
  • 4
  • What exactly are you struggling with? Reading the file and building the graph or just building the graph? You can use some existing graph library for C++ like BGL (documentation is horrible) or Lemon (documentation is better but might be a bit unintuitive at first). Otherwise it seems pretty straightforward to me, no? – Resurrection Apr 24 '16 at 07:09
  • I am struggling with knowing how to read each line in and where to save the data. How do I read in two strings and then two ints and what should I add them to? Arrays, vectors or something else. – M. Meacham Apr 24 '16 at 07:22

1 Answers1

0

I suggest using Lemon, see tutorial: http://lemon.cs.elte.hu/pub/tutorial/a00011.html

Generally speaking you separate structure (the graph) and the data. So in case of lemon you would read each line, split it into 4 fields (delimiter being the whitespace). During the read of the file you should also maintain the hash or map (e.g. std::unordered_map) to quickly lookup destinations already in the graph (or use graph API to find them but that would be slower).

So:

ListDigraph g;
ListDigraph::NodeMap<std::string> gDestinations(g);
ListDigraph::ArcMap<int> gCosts(g);
ListDigraph::ArcMap<int> gDistances(g);
std::unordered_map<std::string, ListDigraph::Node> destinations;

And then for each row:

//first read the line, split it be whitespace into 4 fields, e.g. into these
std::string destFrom, destTo;
int distance, cost;

//first the structure
auto itFrom = destinations.insert(destFrom, g.addNode()).first; //dest is the first or second field in your file
auto itTo = destinations.insert(destTo, g.addNode()).first; //dest is the first or second field in your file
ListDigraph::Arc route = g.addArc(*itFrom, *itTo);  

//then the data
gDestinations[*itFrom] = destFrom; //well this could be done once if the place exists already, this s for brevity
gDestinations[*itTo] = destTo; //dtto
gDistances[route] = distance; //distance is the third field
gCosts[route] = cost; //cost is the fourth field

And that is it. See the tutorial and Lemon documentation how to use graph algorithms and manipulate the graph etc.

Resurrection
  • 3,916
  • 2
  • 34
  • 56