【问题标题】:Building a Directed Graph from a file从文件构建有向图
【发布时间】:2016-04-24 07:01:17
【问题描述】:

我需要读入一个文件并从中构建一个有向图。我正在使用 C++。该文件如下所示:

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

第一行表示从 SFA 到 SLC 的航班为 700 英里,费用为 59 美元,每行都遵循此公式。我很难找到一个好的方法来做到这一点。任何帮助将不胜感激。提前谢谢你。

【问题讨论】:

  • 你到底在纠结什么?读取文件并构建图表还是仅仅构建图表?您可以使用一些现有的 C++ 图形库,例如 BGL(文档很糟糕)或 Lemon(文档更好,但一开始可能有点不直观)。否则对我来说似乎很简单,不是吗?
  • 我正在努力了解如何读取每一行以及将数据保存在哪里。如何读取两个字符串,然后读取两个整数,我应该将它们添加到什么?数组、向量或其他东西。

标签: c++ file graph digraphs


【解决方案1】:

我建议使用Lemon,见教程:http://lemon.cs.elte.hu/pub/tutorial/a00011.html

一般来说,您将结构(图表)和数据分开。因此,如果是柠檬,您将阅读每一行,将其分成 4 个字段(分隔符是空格)。在读取文件期间,您还应该维护哈希或映射(例如 std::unordered_map)以快速查找图中已经存在的目标(或使用图形 API 来查找它们,但这会更慢)。

所以:

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;

然后对于每一行:

//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

就是这样。请参阅教程和 Lemon 文档如何使用图算法和操作图等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多