【问题标题】:generating graph with random edges生成具有随机边的图
【发布时间】: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 上是明确题外话。

标签: c algorithm math random


【解决方案1】:

所以你有 N 条边并且想要标记其中的 K 条优化内存消耗。在这种情况下,您可以使用具有 O(K) 内存复杂度的 Reservoir sampling

创建一个大小为 K 的整数数组,用 0..K-1 个数字填充它,然后循环并使用提供一致性的规则随机替换一些数字

ReservoirSample(S[1..n], R[1..k])
  // fill the reservoir array
  for i = 1 to k
      R[i] := S[i]

  // replace elements with gradually decreasing probability
  for i = k+1 to n
    j := random(1, i)   // important: inclusive range
    if j <= k
        R[j] := S[i]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多