Pagini recente » Cod sursa (job #3294745) | Algoritmiada 2013 - Clasament Runda 3, Clasele 11-12 | Rating Ciobanu Andrei Mihai (amcbn) | Profil Cojocaru_Andrei_Cristian | Cod sursa (job #3294643)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int NMAX = 2e5 + 1, INF = 2e9;
int n, m, mincost[NMAX], parent[NMAX];
bool vis[NMAX];
vector<pair<int, int>> adj[NMAX], tree;
int prim()
{
int ans = 0;
fill(mincost + 1, mincost + n + 1, INF);
fill(parent + 1, parent + n + 1, -1);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, 1});
while(!pq.empty())
{
int cost = pq.top().first, u = pq.top().second; pq.pop();
if(vis[u])
continue;
vis[u] = true;
ans += cost;
if(parent[u] != -1)
tree.push_back({parent[u], u});
for(auto p : adj[u])
{
int v = p.first, weight = p.second;
if(!vis[v] && weight < mincost[v])
{
mincost[v] = weight;
parent[v] = u;
pq.push({weight, v});
}
}
}
return ans;
}
int main()
{
fin >> n >> m;
while(m--)
{
int u, v, cost;
fin >> u >> v >> cost;
adj[u].push_back({v, cost});
adj[v].push_back({u, cost});
}
fout << prim() << "\n" << tree.size() << "\n";
for(auto edge : tree)
fout << edge.first << " " << edge.second << "\n";
return 0;
}