Pagini recente » Cod sursa (job #2183312) | Istoria paginii runda/cdib_8910/clasament | Cod sursa (job #694517) | Cod sursa (job #2194580) | Cod sursa (job #2684763)
#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;
}