素数算法:通过边权重的总和显示相关边
Prim algorithm: show concerned edges with summation of edges weights
我正在尝试修改从这里获取的prim算法,以便不仅能够显示边缘权重的总和,而且还能够显示边缘,并且它无法正常工作。
备注:修改了下面的代码以显示边权重的最大总和。
#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <utility>
using namespace std;
const int MAX = 1e4 + 5;
typedef pair<long long, int> PII;
bool marked[MAX];
vector <PII> adj[MAX];
long long prim(int x)
{
priority_queue<PII, vector<PII>, less<PII> > Q; //changed greater by less
int y;
long long maxCost = 0;
PII p;
Q.push(make_pair(0, x));
while(!Q.empty())
{
// Select the edge with max weight
p = Q.top();
Q.pop();
x = p.second;
// Checking for cycle
if(marked[x] == true)
continue;
maxCost += p.first;
marked[x] = true;
for(int i = 0;i < adj[x].size();++i)
{
y = adj[x][i].second;
if(marked[y] == false){
Q.push(adj[x][i]);
cout << x << '-' << y << endl;
}
}
}
return maxCost;
}
int main()
{
int nodes, edges, x, y;
long long weight, maxCost;
cin >> nodes >> edges;
for(int i = 0;i < edges;++i)
{
cin >> x >> y >> weight;
adj[x].push_back(make_pair(weight, y));
adj[y].push_back(make_pair(weight, x));
}
// Selecting 1 as the starting node
maxCost = prim(1);
cout << maxCost << endl;
return 0;
}
输入
4 5
1 2 7
1 4 6
4 2 9
4 3 8
2 3 6
输出
wrong output expected ouput
1-2 1-4
1-4 2-4
2-4 4-3
2-3 24
4-3
24
在此 cas,我只想显示相关的边缘,但我不知道我需要在哪里显示 x 和 y 值。
如果只想打印构成 MST 的边缘,则需要在从队列中弹出元素后执行此操作。内部for
记录候选项。这些不一定使用。似乎您没有以Q
记录完整的边,而只是记录其权重和目标顶点。如果要打印边缘,还需要存储起始顶点(或者能够以某种方式恢复它)。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- D3D11-将混合权重和索引传递到顶点着色器
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 素数算法:通过边权重的总和显示相关边
- 如何使用我的 if-else 语句根据用户权重的输入执行特定操作,然后将其显示到控制台?