Cod sursa(job #2684763)

Utilizator CraniXortDumitrescul Eduard CraniXort Data 14 decembrie 2020 19:37:28
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

std::ifstream fin("input.txt");
std::ofstream fout("output.txt");

std::vector <std::pair <int, int>> edge[100005];

int cost[100005];
bool ok[100005];

void Prim(int V){
    
    std::priority_queue <std::pair <int, int>, std::vector <std::pair <int, int>>, std::greater <std::pair <int, int>>> pq;
    
    ok[1] = true;
    for(int i=1; i<=V; i++)
        cost[i] = 1e9;

    for(auto next: edge[1]){
        cost[next.first] = next.second;
        pq.push({next.second, next.first});
    }
    long long answer = 0;

    

    for(int it=1, min, node; it<=V-1; it++){
        //min = 1e9;
        // for(int i=1; i<=V; i++){
        //     if(ok[i] == false and cost[i] < min){
        //         min = cost[i];
        //         node = i;
        //     }
        // }

        while(ok[pq.top().second] == true) pq.pop();

        min = pq.top().first;
        node = pq.top().second;

        answer += min;
        ok[node] = 1;
        for(auto next: edge[node]){
            cost[next.first] = std::min(cost[next.first], next.second);
            pq.push({next.second, next.first});
        }
    }

    std::cout << answer;
}

int main(){
    int V, E;
    std::cin >> V >> E;

    for(int i=0, src, dest, cost; i<E; i++){
        std::cin >> src >> dest >> cost;
        edge[src].push_back({dest, cost});
        edge[dest].push_back({src, cost});
    }
    
    Prim(V);

    return 0;
}