C++ - Kruskal algorithm STL
C++ - Kruskal algorithm STL
基于视频编写了Kruskal算法。但我有一个"小"问题——它不是找到最小的权重,而是找到最高的权重。这听起来可能很有趣,但是我不知道我错在哪里了。
collection::collection(int vert){ coll = new SNode[vert]; }
collection::~collection(){}
void collection::Create(int vert)
{
coll[vert].up = vert;
coll[vert].rank = 0;
}
int collection::Find(int vert)
{
/*if (coll[vert].up != vert) coll[vert].up = Find(coll[vert].up);
return coll[vert].up;*/
if (coll[vert].up == vert) return coll[vert].up;
else Find(coll[vert].up);
}
void collection::Union(graf::Edges e)
{
int home, dest;
home = Find(e.v1);
dest = Find(e.v2);
if (home != dest){
if (coll[home].rank > coll[dest].rank){ coll[dest].up = home; }
else if (coll[home].rank < coll[dest].rank){ coll[home].up = dest; }
else{
coll[home].up = dest;
//if (coll[home].rank == coll[dest].rank)
coll[dest].rank++;
}
}
}
和主要算法。权重保存在称为"weightmat"的二维矩阵中。顶点是顶点的数量,边缘是带有变量v1,v2和权重的结构体。使用这个结构体,我创建了一个边数组。:
collection newcollection(vertex);
struct CompareMat{
bool operator()(Edges &node1, Edges &node2){
if (node1.weight < node2.weight) return true;
else return false;
}
};
priority_queue<Edges, vector<Edges>, CompareMat> EdgesQueue;
Edges temp;
Edges* edges = new Edges[edge];
Edges* MSTTree = new Edges[vertex-1];
for (int i = 0; i < vertex; i++){
for (int j = 0; j < vertex; j++)
{
if (nbhmat[i][j] != 0){
edges[i].v1 = i;
edges[i].v2 = j;
edges[i].weight = weightmat[i][j];
}
}
EdgesQueue.push(edges[i]);
}
for (int i = 0; i < vertex; i++){
newcollection.Create(i);
}
for (int i = 1; i < vertex; i++)
{
do
{
temp = EdgesQueue.top();
EdgesQueue.pop();
} while (newcollection.Find(temp.v1) == newcollection.Find(temp.v2));
MSTTree[i - 1] = temp;
newcollection.Union(temp);
}
cout << endl << endl << "Kruskal's algorithm for matrix:" << endl;
for (int i = 0; i < vertex - 1; i++){
cout << MSTTree[i].v1 << " " << MSTTree[i].v2 << " weight " << MSTTree[i].weight << endl;
}
priority_queue
在其顶部有最大的元素(是的,比较器类相当于less
),但您首先需要最小的边。你需要反转你的CompareMat::operator()
比较。
还有两个音符
首先,在CompareMat::operator()
中可以直接返回比较结果:
//return node1.weight < node2.weight; // your version
return node1.weight > node2.weight; // correct version
其次,为什么需要优先队列?一个简单的排序就足够了,因为你似乎没有改变你的边。
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 在C应用程序中运行C++(带有STL)函数
- 使用2个键的cpp-stl::优先级队列排序不正确
- 在STL容器中使用模板类
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 将stl字符串缩小到小于15个字符的容量
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 检查函数返回类型是否与STL容器类型值相同
- STL算法函数在多个一维容器上的使用
- 在STL - C++中按成绩对学生列表进行排序?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- λ可以适应STL吗?
- 为什么使用 NDK 不能存在不同的 stl 实现?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 使用 char 分隔符解析C++中的字符串,但将可重复的字符保留为每个解析的子字符串 (C++ STL) 中的分隔符
- 在C++中迭代 STL 集时出现奇怪的问题<CStudent>
- 如何在 C++17 STL 并行算法中处理调度?
- 在学习数据结构之前对STL有一个了解是好的吗?
- C++ - Kruskal algorithm STL