从文件中读取邻接表

Reading adjacency list from file

我需要从文件邻接列表中读取 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++;
}

您无法同时读取两个数字(重量和目的地)。你准备好让你的思想震撼了吗? 您可以链接输入运算符!

这意味着您可以:

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