"#include \n#include \n#include \n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/connected_components.hpp>\n\n// 定义图类型\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;\n\n// 定义节点类型\ntypedef boost::graph_traits::vertex_descriptor Vertex;\n\nint main() {\n std::ifstream file("adjacency_matrix.txt"); // 读取邻接矩阵文件\n if (!file) {\n std::cerr << "Error opening file." << std::endl;\n return 1;\n }\n\n int numVertices;\n file >> numVertices; // 读取节点数量\n\n // 创建图对象\n Graph g(numVertices);\n\n // 读取邻接矩阵数据并添加边\n for (int i = 0; i < numVertices; ++i) {\n for (int j = 0; j < numVertices; ++j) {\n int value;\n file >> value;\n if (value != 0) {\n boost::add_edge(i, j, g);\n }\n }\n }\n\n file.close();\n\n // 计算节点度\n std::vector degrees(numVertices);\n boost::graph_traits::vertex_iterator vertexIt, vertexEnd;\n for (boost::tie(vertexIt, vertexEnd) = boost::vertices(g); vertexIt != vertexEnd; ++vertexIt) {\n degrees[*vertexIt] = boost::out_degree(*vertexIt, g);\n }\n\n // 计算节点所属的模块\n std::vector component(numVertices);\n int numComponents = boost::connected_components(g, &component[0]);\n\n // 输出结果\n std::cout << "Node degrees:" << std::endl;\n for (int i = 0; i < numVertices; ++i) {\n std::cout << "Node " << i << ": " << degrees[i] << std::endl;\n }\n\n std::cout << "Node components:" << std::endl;\n for (int i = 0; i < numVertices; ++i) {\n std::cout << "Node " << i << ": " << component[i] << std::endl;\n }\n\n return 0;\n}\n"\n\n"假设邻接矩阵数据保存在名为"adjacency_matrix.txt"的文件中,文件格式如下:\n\n\n5 // 节点数量\n0 1 1 0 0\n1 0 0 1 0\n1 0 0 1 0\n0 1 1 0 1\n0 0 0 1 0\n\n\n代码中使用了boost::adjacency_list来表示图,其中boost::vecS用于指定节点容器类型为vector,boost::undirectedS表示图是无向的。boost::add_edge用于添加边,boost::out_degree用于计算节点的度,boost::connected_components用于计算节点的模块。最后,使用std::cout输出结果。\n\n请根据实际情况修改代码中的文件名和文件格式,并根据需要进行适当的调整。"\n


原文地址: https://www.cveoy.top/t/topic/p3Ym 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录