C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

ランダムエッジ生成を使用してランダムグラフを作成するC++プログラム


このプログラムでは、ランダムな頂点とエッジに対してランダムなグラフが生成されます。このプログラムの時間計算量はO(v * e)です。ここで、vは頂点の数、eはエッジの数です。

アルゴリズム

Begin
   Develop a function GenRandomGraphs(), with ‘e’ as the
   number of edges and ‘v’ as the number of vertexes, in the argument list.
      Assign random values to the number of vertex and edges of the graph,
   using rand() function.
      Print the connections of each vertex, irrespective of the
      direction.
      Print “Isolated vertex” for the vertex having no degree.
End

#include<iostream>
#include<stdlib.h>
using namespace std;
void GenRandomGraphs(int NOEdge, int NOVertex)
{
   int i, j, edge[NOEdge][2], count;
   i = 0;
   //Assign random values to the number of vertex and edges
   of the graph, Using rand().
   while(i < NOEdge)
   {
      edge[i][0] = rand()%NOVertex+1;
      edge[i][1] = rand()%NOVertex+1;
      //Print the connections of each vertex, irrespective of
      the direction.
      if(edge[i][0] == edge[i][1])
         continue;
      else
      {
         for(j = 0; j < i; j++)
         {
            if((edge[i][0] == edge[j][0] &&
            edge[i][1] == edge[j][1]) || (edge[i][0] == edge[j][1] &&
            edge[i][1] == edge[j][0]))
            i--;
         }
      }i
      ++;
   }
   cout<<"\nThe generated random graph is: ";
   for(i = 0; i < NOVertex; i++)
   {
      count = 0;
      cout<<"\n\t"<<i+1<<"-> { ";
      for(j = 0; j < NOEdge; j++)
      {
         if(edge[j][0] == i+1)
         {
            cout<<edge[j][1]<<" ";
            count++;
         } else if(edge[j][1] == i+1)
         {
            cout<<edge[j][0]<<" ";
            count++;
         } else if(j== NOEdge-1 && count == 0)
         cout<<"Isolated Vertex!"; //Print “Isolated vertex” for the vertex having no degree.
      }
      cout<<" }";
   }
}
int main()
{
   int i, e, n;
   cout<<"Random graph generation: ";
   n= 7 + rand()%6;
   cout<<"\nThe graph has "<<n<<" vertices";
   e = rand()%((n*(n-1))/2);
   cout<<"\nand has "<<e<<" edges.";
   GenRandomGraphs(e, n);
}

出力

Random graph generation:
The graph has 8 vertices
and has 18 edges.
The generated random graph is:
1-> { 5 4 2 }
2-> { 4 8 6 3 1 5 }
3-> { 5 4 7 2 }
4-> { 2 3 7 1 8 5 }
5-> { 3 1 7 4 2 8 }
6-> { 2 8 7 }
7-> { 4 3 5 6 }
8-> { 2 6 4 5 }

  1. 接続行列を使用してグラフを表現するC++プログラム

    グラフの接続行列は、メモリに保存するグラフの別の表現です。この行列は正方行列ではありません。接続行列の次数はVxEです。ここで、Vは頂点の数、Eはグラフのエッジの数です。 この行列の各行に頂点を配置し、各列にエッジを配置します。エッジe{u、v}のこの表現では、列eの場所uとvに対して1でマークされます。 隣接行列表現の複雑さ 接続行列表現は、計算中にO(Vx E)のスペースを取ります。完全グラフの場合、エッジの数はV(V-1)/2になります。したがって、接続行列はメモリ内でより大きなスペースを取ります。 入力 出力 E0 E1 E2

  2. 隣接行列を使用してグラフを表現するC++プログラム

    グラフの隣接行列は、サイズV x Vの正方行列です。Vは、グラフGの頂点の数です。この行列では、各辺にV個の頂点がマークされています。グラフにiからjの頂点までのエッジがある場合、i thの隣接行列に 行とjth 列は1(または加重グラフの場合はゼロ以外の値)になります。それ以外の場合、その場所は0を保持します。 隣接行列表現の複雑さ 隣接行列表現はO(V 2 )計算中のスペースの量。グラフに最大数のエッジと最小数のエッジがある場合、どちらの場合も必要なスペースは同じになります。 入力 出力 0 1 2 3 4 5