C++ 程序生成给定边数的随机无向图
c++server side programmingprogramming
这是一个 C++ 程序,我们为给定的边"e"生成一个无向随机图。该算法基本上在大型网络上实现,该算法的时间复杂度为 O(log(n))。
算法
开始 函数 GenerateRandomGraphs(),在参数列表中将"e"作为边数。 初始化 i = 0 while(i < e) edge[i][0] = rand()%N+1 edge[i][1] = rand()%N+1 增加 I; 对于 i = 0 到 N-1 初始化计数 = 0 对于 j = 0 到 e-1 if(edge[j][0] == i+1) 打印 edge[j][1] 增加计数 else if(edge[j][1] == i+1) 打印 edge[j][0] 增加计数 else if(j == e-1 && count == 0) 打印孤立顶点 结束
示例
#include<iostream> #include<stdlib.h> #define N 10 using namespace std; void GenerateRandomGraphs(int e) { int i, j, edge[e][2], count; i = 0; // 生成两个随机数之间的连接,为了抽取一个小的例子,限制顶点的数量为 10。 while(i < e) { edge[i][0] = rand()%N+1; edge[i][1] = rand()%N+1; i++; } //打印每个顶点的所有连接,与方向无关。 cout<<"\n生成的随机图为:"; for(i = 0; i < N; i++) { count = 0; cout<<"\n\t"<<i+1<<"-> { "; for(j = 0; j < e; j++) { if(edge[j][0] == i+1) { cout<<edge[j][1]<<&" & ";; count++; } else if(edge[j][1] == i+1) { cout<<edge[j][0]<<&" & ";; count++; } //为度数为零的顶点打印"Isolated Vertex"。 else if(j == e-1 && count == 0) cout<<&"Isolated Vertex!"; } cout<<" }"; } } int main() { int n, i ,e; cout<<"输入随机图的边数:"; cin>>e; GenerateRandomGraphs(e); }
输出
输入随机图的边数:10 生成的随机图为: 1-> { 10 7 } 2-> { 10 } 3-> { 7 8 7 } 4-> { 7 6 7 } 5-> { Isolated Vertex! } 6-> { 8 4 } 7-> { 4 3 4 1 3 } 8-> { 6 3 } 9-> { Isolated Vertex! } 10-> { 2 1 }