[英]How to sort a graph base on the edges degree in C++
I'm new with C++ and sort algorithms.我是 C++ 和排序算法的新手。 I would like to have the ordered list of vertexes based on their degrees.我想根据它们的度数排序顶点列表。
I'm constructing my graph as below:我正在构建我的图表,如下所示:
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
int main(){
int V = 4;
vector<int> adj[V];
addEdge(adj, 0, 2);
addEdge(adj, 0, 1);
addEdge(adj, 0, 3);
addEdge(adj, 2, 1);
printGraph(adj, V);
return 0;
} }
Output desirable: Output 可取:
Someone can help me indicating how can I solve this?有人可以帮我指出我该如何解决这个问题? I appreciate it!我很感激!
Create an vector of vertex indices and sort them in descending order of vector sizes in adj
.创建一个顶点索引向量,并在adj
中按向量大小的降序对它们进行排序。 You can use std::sort
(or std::stable_sort
in case elements with the same degree should be ordered in ascending order of vertex indices) passing a comparison object to sort the indices:您可以使用std::sort
(或std::stable_sort
以防具有相同度数的元素应按顶点索引的升序排序)通过比较 object 对索引进行排序:
void printGraph(std::vector<int> const* adj, size_t count)
{
std::vector<size_t> indices;
for (size_t i = 0; i != count; ++i)
{
indices.push_back(i);
}
std::stable_sort(indices.begin(), indices.end(), [=](size_t index1, size_t index2)
{
return adj[index1].size() > adj[index2].size();
});
for (auto index : indices)
{
std::cout << "Vertex " << index << ", degree " << adj[index].size() << '\n';
}
}
If you only want to sort it, there are sorting functions in the standard libraries, but if you want to implement it yourself, a good approach for a beginner is the insertion sort .如果你只想排序,标准库中有排序功能,但如果你想自己实现,对于初学者来说,插入排序是一个不错的方法。 It is not the most efficient method, but it is easy to understand and clean to implement.这不是最有效的方法,但它很容易理解并且易于实施。
Here's a possible implementation for your case:这是您的案例的可能实现:
vector<int> sortedVertices(vector<int> adj[], int size){
vector<int> result;
vector<int> degrees;
for(int vertex=0; vertex < size; vertex++){
// calculate the degree of the vertex and store it
int degree = adj[vertex].size();
degrees.push_back(degree);
// look for the first position in the result where the degree is
// lesser than the current vertex degree and insert it there (or in
// the end of the list, if it is the smallest)
int pos = 0;
while(pos < result.size() && degree < degrees[result[pos]]){
pos++;
}
result.insert(result.begin()+pos, vertex);
}
// Now you can print it if you want
for(int i=0; i < result.size(); i++){
cout << "Vertex " << result[i] << ", degree" << degrees[result[i]] << endl;
}
return result;
}
So you can use it in your case like this:所以你可以像这样在你的情况下使用它:
int V = 4;
vector<int> adj[V];
addEdge(adj, 0, 2);
addEdge(adj, 0, 1);
addEdge(adj, 0, 3);
addEdge(adj, 2, 1);
printGraph(adj, V);
sortedVertices(adj, V);
return 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.