Cod sursa(job #3259779)

Utilizator ShAwDoRneYNacu Gabriel ShAwDoRneY Data 27 noiembrie 2024 19:46:24
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

vector<pair<int,int>> path;

int MST(int weight, int node, int noNodes, vector<vector<pair<int,int>>> &graph) {

    vector<bool> isVisited(noNodes+1, 0);
    vector<int> parent(noNodes+1, -1);
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> Q;

    Q.push({weight, node});

    int answer = 0;

    while(!Q.empty()) {
        int currentNode = Q.top().second;
        int currentWeight = Q.top().first;
        Q.pop();

        if(isVisited[currentNode] == true)
            continue;
        
        isVisited[currentNode] = true;
        answer += currentWeight;

        if(parent[currentNode] != -1)
            path.push_back({currentNode, parent[currentNode]});

        for(auto neighbor : graph[currentNode]) {
            if(!isVisited[neighbor.second]) {
                Q.push({neighbor.first, neighbor.second});
                if(parent[neighbor.second] == -1)
                    parent[neighbor.second] = currentNode;
            }
                
        }
    }
    return answer;

}

int main() {

    int noNodes, noEdges;
    vector<vector<pair<int,int>>> graph;
    fin >> noNodes >> noEdges;
    graph.resize(noNodes+1);

    while(noEdges--) {
        int firstNode, secondNode, weight;
        fin >> firstNode >> secondNode >> weight;
        graph[firstNode].push_back({weight,secondNode});
        graph[secondNode].push_back({weight,firstNode});
    }

    fout << MST(0, 1, noNodes, graph) << endl << noNodes-1 << endl;



    return 0;
}