#include \n#include \n#include \n#include \n\nusing namespace std;
\n// 定义边的结构体\nstruct Edge {\n int src, dest; \n double weight; \n};\n\n// 定义比较函数,用于边的排序\nbool compareEdges(Edge e1, Edge e2) {\n return e1.weight < e2.weight; \n}\n\n// 查找节点的根节点\nint findRoot(vector& parent, int node) {\n if(parent[node] == -1)\n return node; \n return findRoot(parent, parent[node]); \n}\n\n// 合并两个节点的集合\nvoid unionSets(vector& parent, int root1, int root2) {\n parent[root1] = root2; \n}\n\n// 使用Kruskal算法构建最小生成树\nvoid kruskalMST(vector& edges, int numVertices) {\n // 对边进行排序\n sort(edges.begin(), edges.end(), compareEdges); \n\n vector parent(numVertices, -1); // 存储父节点\n vector result; // 存储最小生成树的边\n\n int numEdges = 0; // 记录已选择的边数\n\n for(int i = 0; numEdges < numVertices - 1; i++) {\n int root1 = findRoot(parent, edges[i].src); \n int root2 = findRoot(parent, edges[i].dest); \n\n if(root1 != root2) {\n // 如果两个节点不在同一个集合中,则选择该边\n result.push_back(edges[i]); \n unionSets(parent, root1, root2); \n numEdges++; \n } \n } \n\n // 输出最小生成树的边\n for(int i = 0; i < result.size(); i++) {\n cout << result[i].src << " - " << result[i].dest << " : " << result[i].weight << endl; \n } \n}\n\nint main() {\n string filename = "point_cloud.ply"; \n\n ifstream file(filename); \n if(!file) {\n cerr << "Error opening file." << endl; \n return 1; \n } \n\n string line; \n bool startData = false; \n int numVertices = 0; \n vector edges; \n\n // 读取PLY文件\n while(getline(file, line)) {\n if(line.find("element vertex") != string::npos) {\n numVertices = stoi(line.substr(15)); \n } \n else if(line.find("end_header") != string::npos) {\n startData = true; \n } \n else if(startData) {\n vector vertexCoords; \n size_t pos = 0; \n string token; \n\n while((pos = line.find(" ")) != string::npos) {\n token = line.substr(0, pos); \n vertexCoords.push_back(stod(token)); \n line.erase(0, pos + 1); \n } \n\n int numCoords = vertexCoords.size(); \n for(int i = 0; i < numCoords; i++) {\n for(int j = i + 1; j < numCoords; j++) {\n Edge e; \n e.src = i; \n e.dest = j; \n e.weight = abs(vertexCoords[i] - vertexCoords[j]); // 使用坐标差作为边的权重\n edges.push_back(e); \n } \n } \n } \n } \n\n file.close(); \n\n kruskalMST(edges, numVertices); \n\n return 0; \n}


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

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