将最小生成树的各个节点根据1个邻近点2个邻近点3个邻近点分为三类的c++代码
以下是将最小生成树的节点根据邻近点数分为三类的C++代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 邻接表存储图
vector<vector<pair<int, int>>> graph;
// 最小生成树的边
vector<pair<int, int>> mst;
// 节点的邻近点数
vector<int> neighborCount;
// 计算节点的邻近点数
void calculateNeighborCount() {
for (int i = 0; i < graph.size(); i++) {
int count = graph[i].size();
for (auto edge : mst) {
if (edge.first == i || edge.second == i) {
count--;
}
}
neighborCount[i] = count;
}
}
// 将节点根据邻近点数分为三类
void classifyNodes(vector<int>& type1, vector<int>& type2, vector<int>& type3) {
for (int i = 0; i < neighborCount.size(); i++) {
if (neighborCount[i] == 1) {
type1.push_back(i);
} else if (neighborCount[i] == 2) {
type2.push_back(i);
} else if (neighborCount[i] >= 3) {
type3.push_back(i);
}
}
}
// Prim算法计算最小生成树
void prim(int start) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<bool> visited(graph.size(), false);
visited[start] = true;
for (auto edge : graph[start]) {
pq.push(edge);
}
while (!pq.empty()) {
auto edge = pq.top();
pq.pop();
if (visited[edge.second]) {
continue;
}
visited[edge.second] = true;
mst.push_back(edge);
for (auto nextEdge : graph[edge.second]) {
if (!visited[nextEdge.second]) {
pq.push(nextEdge);
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
graph.resize(n);
neighborCount.resize(n);
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back(make_pair(w, v));
graph[v].push_back(make_pair(w, u));
}
prim(0);
calculateNeighborCount();
vector<int> type1, type2, type3;
classifyNodes(type1, type2, type3);
cout << "Type 1 nodes: ";
for (auto node : type1) {
cout << node << " ";
}
cout << endl;
cout << "Type 2 nodes: ";
for (auto node : type2) {
cout << node << " ";
}
cout << endl;
cout << "Type 3 nodes: ";
for (auto node : type3) {
cout << node << " ";
}
cout << endl;
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/fqty 著作权归作者所有。请勿转载和采集!