【发布时间】:2017-10-17 09:50:25
【问题描述】:
我正在尝试编写使用不相交集的 ac/c++ 程序,该程序使用按秩联合和路径压缩图算法,然后在该图上应用 Kruskal 算法。我已经生成 number_of_vertices-1 对 (0,1),(1,2 )...(n-2,n-1) 作为图中的边,以使图连通。我需要生成其余 3*number_Of_Vertices+1 个随机边作为 (vertex1,vertex2) 对而不会发生冲突(同一边不得生成两次)。我必须在不使用额外内存的情况下执行此操作。额外的内存是指一个额外的列表,向量......你知道如何做到这一点吗?
这是我到现在为止所做的,但肯定有冲突:
edge** createRandomEdges(nodeG **nodeArray, int n) {
edge **edgeArray = (edge**)malloc(sizeof(edge*)*n * 4);
for (int i = 0; i < n; i++)
edgeArray[i] = createEdge(nodeArray[0], nodeArray[i + 1], rand() % 100+1);
for (int i = n; i < 4 * n; i++) {
int nodeAindex = rand() % n;
int nodeBindex = rand() % n;
while (nodeAindex == nodeBindex) {
nodeAindex = rand() % n;
nodeBindex = rand() % n;
}
int weight = rand() % 100 + 1;
edgeArray[i] = createEdge(nodeArray[nodeAindex], nodeArray[nodeBindex], weight);
}
return edgeArray;
}
【问题讨论】:
-
您在寻找 c 或 c++ 解决方案吗?两种语言都提供不同的解决方案。您的示例看起来像 c,并且您标记了两种语言。
-
我擅长任何语言解决方案,我只想要算法。是的,我的代码是用 C 编写的
-
如果您想讨论算法,您可能想在更合适的堆栈交换网站上提问。也许cs.stackexchange.com?
-
@FrançoisAndrieux 算法在 SO 上不是题外话,编程问题在 cs.stackexchange 上是明确题外话。