#include <vector>
#include <queue>
using namespace std;

int solution(int n, vector<vector<int>> costs) {
    vector<vector<pair<int, int>>> graph(n);
    
    for (auto& edge : costs)
    {
        int u = edge[0], v = edge[1], cost = edge[2];
        graph[u].push_back({cost, v});
        graph[v].push_back({cost, u});
    }
    
    int totalCost = 0;
    vector<bool> visited(n, false);
    
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    
    visited[0] = true;
    for (auto& edge : graph[0])
    {
        pq.push(edge);
    }
    
    while (!pq.empty())
    {
        auto [cost, next] = pq.top();
        pq.pop();
        
        if (visited[next] == true)
            continue;
        
        visited[next] = true;
        totalCost += cost;
        
        for (auto& edge : graph[next])
        {            
            if (visited[edge.second] == false)
                pq.push(edge);
        }
    }
    
    return totalCost;
}

+ Recent posts