我正在尝试在给定某些图形边缘(可以将其视为网络)的情况下生成有效树。以下是从文件中读取图形边缘的代码;
FILE *fin = fopen("somefile.txt", "r");
for (int i = 0; i <=edges; i++) {
fscanf(fin, "%d%d%d", &u, &v, &w);
graph[u][v]=w;
}
fclose(fin);
现在我想为给定的根u
生成最大数量的可能树(或拓扑),并给定这些边缘的给定大小N
。
例如,如果有边缘; 1 ---&gt; 2; 1 ---&gt; 3; 3 ---→4。现在如果N是1; u = 1的可能树是1 ----> 2和1 ---> 3。如果N是2,那么可能的树是1 ---> 2&amp; 3或1 ---&gt; 3 ----&gt; 4 实现这一目标的最佳方式是什么?我不关心复杂性问题。我很感激你的帮助!
答案 0 :(得分:0)
它可能不是最佳实施但是 这样的事情应该有效
map<vertex,list<edge>> vertexToedgeThatIncludeIt
void Coloredge(edgeList)
{
for each edge in list:
edge.color=True
}
void init()
{
for each edge:
{
vertexToedgeThatIncludeIt[edge.vertex1].append(edge)
vertexToedgeThatIncludeIt[edge.vertex2].append(edge)
}
}
edge* findUnColoredvertex(edgeList,startPoistion,founfAt)
{
skip to startPoistion
for each edge In edgeList:
if edge not colored return edge
update founfAt
return NULL
}
void spanTree(vertexToedgeThatIncludeIt,spanTreeList,lastvertex)
{
if(spanTreeList.size==NumberOfTotalvertex)
{
print spanningTree
return
}
nextedge=findUnColoredvertex(vertexToedgeThatIncludeIt[lastvertex],0,founfAt)
while(nextedge!=NULL)
{
spanTreeList.append(nextedge);
Coloredge(vertexToedgeThatIncludeIt[lastvertex]);
spanTree(vertexToedgeThatIncludeIt,spanTreeList,nextedge.othervertex)
spanTreeList.pop();
UnColoredge(vertexToedgeThatIncludeIt[lastvertex])
nextedge=findUnColoredvertex(vertexToedgeThatIncludeIt[lastvertex],founfAt,founfAt)
}
}