Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Prim算法:通过边权重的总和显示相关边_C++_Graph Algorithm - Fatal编程技术网

C++ Prim算法:通过边权重的总和显示相关边

C++ Prim算法:通过边权重的总和显示相关边,c++,graph-algorithm,C++,Graph Algorithm,我试图修改这个prim算法,使它不仅能够显示边权重的总和,而且能够显示边,它不能正常工作 备注:修改下面的代码以显示边权重的最大总和。 #include <iostream> #include <vector> #include <queue> #include <functional> #include <utility> using namespace std; const int MAX = 1e4 + 5; typedef p

我试图修改这个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;
}
输出

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的边,则需要在从队列中弹出一个元素后执行此操作。的内部
记录候选项。这些不一定要使用。似乎在
Q
中记录的不是完整的边,而是它的权重和目标顶点。如果要打印边,还需要存储起始顶点(或以某种方式恢复它)。

如果只打印构成MST的边,则需要在从队列中弹出元素后执行此操作。
的内部
记录候选项。这些不一定要使用。似乎在
Q
中记录的不是完整的边,而是它的权重和目标顶点。如果要打印边,还需要存储起始顶点(或以某种方式恢复它)

wrong output   expected ouput   

1-2            1-4
1-4            2-4
2-4            4-3
2-3            24
4-3
24