Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.6 kB
1
Indexable
Never

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int INF = 1e9;
vector<vector<pair<int, int>>> adj; // graful dat
vector<int> dist, parent; // vectorii de distante si de parinti
vector<bool> visited; // vectorul de vizitare a nodurilor
void prim(int start) {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    dist[start] = 0;
    pq.push({0, start});
    while(!pq.empty()) {
        int u = pq.top().second;
        pq.pop();
        if(visited[u]) continue;
        visited[u] = true;
        for(auto v : adj[u]) {
            int neighbor = v.first;
            int weight = v.second;
            if(!visited[neighbor] && weight < dist[neighbor]) {
                dist[neighbor] = weight;
                parent[neighbor] = u;
                pq.push({dist[neighbor], neighbor});
            }
        }
    }
}
int main() {
    int n, m;
    cin >> n >> m;
    adj.resize(n+1);
    dist.resize(n+1, INF);
    visited.resize(n+1, false);
    parent.resize(n+1, -1);
    for(int i = 0; i < m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    int start = 1; // putem alege orice nod ca start
    prim(start);
    int totalCost = 0;
    for(int i = 1; i <= n; i++) {
        if(parent[i] != -1) {
            cout << parent[i] << " - " << i << " : " << dist[i] << endl;
            totalCost += dist[i];
        }
    }
    cout << "Costul total al arborelui minim de acoperire este: " << totalCost << endl;
    return 0;
}