Pagini recente » Cod sursa (job #803728) | Cod sursa (job #2547619) | Cod sursa (job #2882774) | Cod sursa (job #3187834) | Cod sursa (job #3238508)
#include <bits/stdc++.h>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
const int nmax=2e5, mmax=4e5, inf=1e9;
vector <pair<int, int>> g[nmax+1];
bitset <nmax+1> used;
int n, m, cost[nmax+1];
vector <pair<int, int>> sol;
void prim()
{
int rez=0;
priority_queue < pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>> > pq;
//costul, nodul nou, nodul vechi
for(int i=1; i<=n; i++)
cost[i]=inf;
for(auto it:g[1])
{
cost[it.first]=it.second;
pq.push({it.second, {it.first, 1} });
}
used[1]=1;
for(int i=1; i<n; i++)
{
while(used[pq.top().second.first]==1)//trebuie sa l iau pe cel care are nodul nou nefolosit
pq.pop();
int drum=pq.top().first, nod=pq.top().second.first;
used[nod]=1;
sol.push_back({pq.top().second.second, nod});
rez+=pq.top().first;
for(auto it:g[nod])
{
cost[it.first] = min(cost[it.first], it.second);
pq.push({it.second, {it.first, nod} });
}
}
out<<rez<<'\n'<<n-1<<'\n';
for(auto it:sol)
{
out<<it.first<<" "<<it.second<<'\n';
}
return;
}
int main()
{
int x, y, c;
in>>n>>m;
for(int i=1; i<=m; i++)
{
in>>x>>y>>c;
g[x].push_back({y, c});
g[y].push_back({x, c});
}
prim();
return 0;
}