【问题标题】:Reading adjacency list from file从文件中读取邻接表
【发布时间】:2018-11-20 19:44:50
【问题描述】:

我需要从文件邻接列表中读取 Kruskal 的算法。输入文件是

9 17
2 3 8 4 9 8
1 3 3 6 4 5 9 6
2 6 4 4 9 1
2 5 3 4 5 3 9 2
4 3 6 1 9 5
5 1 7 5 9 2
6 5 8 4 9 2
1 4 7 4 9 2
1 8 2 6 3 1 4 2 5 5 6 2 7 2 8 2

让我解释一下如何看待这个问题。第一行显然是顶点和边的数量。每下一行表示一个顶点,因此第二行是第一个顶点,它包含将与之连接的顶点和边的权重。以下是第一行的示例。

Vertex 1[Source]: 2[Destination] 3[Weight of the edge] 8[Destination] 4[Weight] 9[Destination] 8[Weight]

我需要将边存储在数组中

typedef struct Edge{
int weight;
int beg, end;
}*PEdge;

问题是我不知道如何将它读入数组。我想出了类似的方法,但显然它不起作用。

    in.open("In0303.txt");
out.open("Out0303.txt");
if(!in || !out)
return 0;
in>>n>>m;
Edge E[34];
while (! in.eof() ){
getline( in, line );
istringstream is( line );
while( is >> number ) {
edge++;
E[edge].beg=row;
E[edge].end=number;
E[edge].weight=number;
}
row++;
}

【问题讨论】:

  • 为什么您的代码“显然”不起作用?它的作用是什么?您期待什么?
  • 在内部 while 循环中,我一次只能读取一个数字,但我需要读取目标并权重将它们保存在数组中的正确索引中,然后在下一次迭代中移动到下一对并递增边缘

标签: c++ algorithm file adjacency-list kruskals-algorithm


【解决方案1】:

sounds like 您无法同时读取两个数字(重量和目的地)。你准备好大开眼界了吗? 您可以链接输入运算符!

这意味着你可以这样做:

int dest, weight;
while( is >> dest >> weight ) {
    edge++;
    E[edge].beg = row;
    E[edge].end = dest;
    E[edge].weight = weight;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多