Pagini recente » Cod sursa (job #1942667) | Cod sursa (job #2904000) | Cod sursa (job #1803333) | Cod sursa (job #829851) | Cod sursa (job #1609740)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");
const int nmax = 200005;
const int mmax = 400005;
vector <pair<int,int> > apm;
int dad[nmax], rang[nmax], n, m, cmin;
struct muchie
{
int x, y, c;
inline bool operator () (const muchie &a, const muchie &b)
{
return a.c < b.c;
}
} g[mmax];
inline int Find(int x)
{
while(dad[x]!=x) x=dad[x];
return x;
}
inline void Union(int x, int y)
{
if(rang[x] > rang[y]) dad[y]=x;
else dad[x]=y;
if(rang[x]==rang[y]) rang[y]++;
}
void kruskal()
{
int rx, ry, i;
for(i=1; i<=n; i++)
dad[i]=i;
sort(g+1, g+m+1, muchie());
for(i=1; i<=m; i++)
{
rx=Find(g[i].x);
ry=Find(g[i].y);
if(rx!=ry)
{
cmin=cmin+g[i].c;
apm.push_back(make_pair(g[i].x, g[i].y));
Union(rx, ry);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
vector <pair<int,int> > :: iterator it;
fin >> n >> m;
for(int i=1; i<=m; i++)
fin >> g[i].x >> g[i].y >> g[i].c;
kruskal();
fout << cmin << "\n" << n-1 << "\n";
for(it=apm.begin(); it!=apm.end(); it++)
fout << it->first << " " << it->second << "\n";
fin.close();
fout.close();
return 0;
}