【发布时间】: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