C++ 程序检查是否有可能为给定的度数序列构造任何图
c++server side programmingprogramming更新于 2024/9/30 19:35:00
这是一个程序,用于检查在给定的度数序列中构造图的可能性。
输入
它需要边和顶点的数量。
输出
它显示创建的图的随机值。
算法
开始 声明一个函数 RandomGraphs()。 声明整数数据类型的 NoEdge 和 NoVertex 并将它们作为参数传递。 声明整数数据类型的 i、j、e[NoEdge][2]、c。 初始化 i = 0。 while (i < NoEdge) do e[i][0] = rand()%NoVertex+1。 e[i][1] = rand()%NoVertex+1。 if(e[i][0] == e[i][1]) then continue。 else for(j = 0; j < i; j++) if((e[i][0] == e[j][0] && e[i][1] == e[j][1]) || (e[i][0] == e[j][1] && e[i][1] == e[j][0])) then i--. i++. 打印"随机生成的图:"。 for(i = 0 to NoVertex-1) c = 0; 打印"顶点数"。 打印顶点数。 for(j = 0 to NoEdge-1) if(e[j][0] == i+1) then 打印 e[j][1] 的值。 c++. else if(e[j][1] == i+1) then 打印 e[j][0] 的值。 c++. else if(j == NoEdge-1 and c == 0) then 打印 "This vertex isisolated!!!". End Begin 声明整型数据类型的 edg, ver。 打印"生成一个随机图:"。 打印"输入图的顶点数:"。 输入 ver 变量的值。 打印"输入图的边数:"。 输入 edg 变量的值。 调用 RandomGraphs(edg, ver) 生成一个具有 edg 个边和 ver 个顶点的随机无向图。 结束。
示例
#include<iostream> #include<stdlib.h> using namespace std; void RandomGraphs(int NoEdge, int NoVertex) { // 生成随机图。 int i, j, e[NoEdge][2], c; i = 0; while(i < NoEdge) { // 在两个顶点之间建立连接 e[i][0] = rand()%NoVertex+1; e[i][1] = rand()%NoVertex+1; if(e[i][0] == e[i][1]) continue; else { for(j = 0; j < i; j++) { if((e[i][0] == e[j][0] && e[i][1] == e[j][1]) || (e[i][0] == e[j][1] && e[i][1] == e[j][0])) i--; } } i++; } cout<<"The randomly generated graph: \n"; for(i = 0; i < NoVertex; i++) { // printing the graph c = 0; cout<<"Vertex number "<<i+1<<": \t { "; for(j = 0; j < NoEdge; j++) { if(e[j][0] == i+1) { cout<<e[j][1]<<" "; c++; } else if(e[j][1] == i+1) { cout<<e[j][0]<<" "; c++; } else if(j == NoEdge-1 && c == 0) cout<<"This vertex is isolated!!!"; } cout<<" }\n"; } } int main() { int edg, ver; cout<<"生成随机图:"; // 输入顶点和边。 cout<<"\n输入图的顶点数:"; cin>>ver; cout<<"\n输入图的边数:"; cin>>edg; RandomGraphs(edg, ver); // 调用函数生成一个有 edg 边和 ver 顶点的随机无向图。 }
输出
随机图的生成: 输入图的顶点数:5 输入图的边数:5 随机生成的图: 顶点 1:{ 5 3 } 顶点 2:{ 3 5 } 顶点 3:{ 2 5 1 } 顶点 4:{ 此顶点是孤立的!!! } 顶点 5:{ 1 3 2 }