Pagini recente » Cod sursa (job #2445552) | Cod sursa (job #2968497) | Cod sursa (job #1729195) | Cod sursa (job #2383450) | Cod sursa (job #2844752)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct str
{
int cost;
int node;
int from;
};
const int NMAX = 2e5 + 2, INF = 1e9;
vector <pair <int, int>> G[NMAX];
int n, m, total;
int d[NMAX], T[NMAX];
bool sel[NMAX];
auto cmp = [](str a, str b)
{
if (!(a.cost < b.cost))
return 1;
return 0;
};
priority_queue <str, vector <str> , decltype(cmp)> H(cmp);
void Init(int S)
{
for(int i = 1; i <= n; ++ i)
d[i] = INF;
d[S] = 0;
sel[S] = true;
return;
}
void Prim(int S)
{
Init(S);
for(auto it: G[S]) {
d[it.second] = (it.first < d[it.second] ? it.first : d[it.second]);
H.push({it.first, it.second, S});
}
while(!H.empty()) {
while(!H.empty() && sel[H.top().node])
H.pop();
if(H.empty())
return;
int node = H.top().node;
int cost = H.top().cost;
int from = H.top().from;
total += cost;
sel[node] = true;
T[node] = from;
H.pop();
for(auto it: G[node]) {
if(!sel[it.second])
H.push({it.first, it.second, node});
}
}
}
int main()
{
fin >> n >> m;
int a, b, cost;
for(int i = 1; i <= m; i++) {
fin >> a >> b >> cost;
G[a].push_back({cost, b});
G[b].push_back({cost, a});
}
Prim(1);
fout << total << '\n' << n - 1 << '\n';
for(int i = 1; i <= n; ++i){
if(i != 1)
fout << i << " " << T[i] << '\n';
}
return 0;
}