c++ - 生成随机 DAG

标签 c++ c algorithm graph cycle

我正在解决一个关于有向无环图的问题。

但我无法在一些有向无环图上测试我的代码。测试图应该很大,并且(显然)是非循环的。

我尝试了很多代码来生成无环有向图。但我每次都失败了。

是否有一些现有的方法可以生成我可以使用的无环有向图?

最佳答案

我编写了一个 C 程序来执行此操作。关键是对节点进行“排序”,从排名较低的节点向排名较高的节点绘制边。

我编写的程序打印在 the DOT language .

这是代码本身,注释解释了它的含义:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MIN_PER_RANK 1 /* Nodes/Rank: How 'fat' the DAG should be.  */
#define MAX_PER_RANK 5
#define MIN_RANKS 3    /* Ranks: How 'tall' the DAG should be.  */
#define MAX_RANKS 5
#define PERCENT 30     /* Chance of having an Edge.  */

int main (void)
{
  int i, j, k,nodes = 0;
  srand (time (NULL));

  int ranks = MIN_RANKS
              + (rand () % (MAX_RANKS - MIN_RANKS + 1));

  printf ("digraph {\n");
  for (i = 0; i < ranks; i++)
    {
      /* New nodes of 'higher' rank than all nodes generated till now.  */
      int new_nodes = MIN_PER_RANK
                      + (rand () % (MAX_PER_RANK - MIN_PER_RANK + 1));

      /* Edges from old nodes ('nodes') to new ones ('new_nodes').  */
      for (j = 0; j < nodes; j++)
        for (k = 0; k < new_nodes; k++)
          if ( (rand () % 100) < PERCENT)
            printf ("  %d -> %d;\n", j, k + nodes); /* An Edge.  */

      nodes += new_nodes; /* Accumulate into old node set.  */
    }
  printf ("}\n");
  return 0;
}

这是从测试运行生成的图表:

A randomly generated DAG

关于c++ - 生成随机 DAG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12790337/

相关文章:

algorithm - 绘制一个距离基点一定距离的点

c++ - 在设置容器的 find() 上崩溃

c++ - 在 C++ 中将包含方法定义的类声明放在头文件中是否被认为是错误的形式?

c++ - NULL 是否在 C++11 中定义为 nullptr?

c - 将 double 除以 0 的 double 给出表达式的极限而不是错误

algorithm - FIFO 页面替换策略是否有可能胜过 LRU?

c++ - 为什么我的 mutator 函数没有设置任何内容?还是我的构造函数?

c - 如何在 C 中定义矩形的框架

c++ - 计时器精度 : c clock( ) vs. WinAPI 的 QPC 或 timeGetTime( )

algorithm - 快速检查集合是否是存储集合的超集