Cod sursa(job #2936343)

Utilizator radubuzas08Buzas Radu radubuzas08 Data 8 noiembrie 2022 17:53:32
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
//
// Created by Radu Buzas on 08.11.2022.
//

#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream in("apm.in");
ifstream out("apm.out");

vector<vector<pair<int, int>>> graph;
vector<int> sol;
int n, m, costTotal;

struct muchie{
    int cost, x, y;
    bool operator<(const muchie o) const{
        return this-> cost > o.cost;
    }
};

void prim(int x){
    vector<bool> visited(n+1);
    visited[x] = 1;
    priority_queue<muchie> q;
    for(auto m : graph[x]) {
        muchie V;
        V.cost = m.second;
        V.y = m.first;
        V.x = x;
        q.push(V);
    }
    while (!q.empty()){
        muchie k = q.top();
        q.pop();
        if(visited[k.y] == 0) {
            costTotal += k.cost;
            visited[k.y] = 1;
            for (auto m: graph[k.y]) {
                muchie V;
                V.cost = m.second;
                V.y = m.first;
                V.x = k.y;
                q.push(V);
            }
        }
    }
}

int main(){
    in >> n >> m;
    graph.resize(n+1);
    for(int i = 1; i <= m; ++i){
        int x, y, c;
        in >> x >> y >> c;
        graph[x].push_back({y, c});
        graph[y].push_back({y, c});
    }
    prim(1);
}