Pagini recente » Cod sursa (job #824290) | Cod sursa (job #1197403) | Cod sursa (job #603715) | Cod sursa (job #2670955) | Cod sursa (job #1670611)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
vector <pair<int,int>> G[200005];
int n,m;
const int INF = 1e9;
void prim(int nod)
{
vector <int> dist(n+1,INF);
vector <int> edge(n+1,-1);
set<pair<int,int>> s;
dist[nod]=0;
for(int i=2;i<=n;i++)
s.insert({dist[i],i});
s.insert({0,1});
while(!s.empty())
{
int u = s.begin() ->second;
s.erase(s.begin());
for(auto p:G[u])
if(dist[p.first]>p.second)
{
s.erase({dist[p.first],p.first});
edge[p.first]=u;
dist[p.first]=p.second;
s.insert({dist[p.first],p.first});
}
}
int total=0;
for(int i=2;i<=n;i++)
total+=dist[i];
g<<total<<"\n"<<n-1<<"\n";
for(int i=2;i<=n;i++)
g<<i<<" "<<edge[i]<<"\n";
}
int main()
{
int a,b,c;
f>>n>>m;
for(int i=0;i<m;i++)
{
f>>a>>b>>c;
G[a].push_back(make_pair(b,c));
G[b].push_back(make_pair(a,c));
}
prim(1);
}