Pagini recente » Cod sursa (job #478607) | Cod sursa (job #951720) | Cod sursa (job #908911) | Cod sursa (job #3207960) | Cod sursa (job #557207)
Cod sursa(job #557207)
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;
#define DIM 400001
ofstream fout("apm.out");
ifstream fin("apm.in");
void Read();
void Kruskal();
void Write();
int Find(int );
void Union(int, int);
int n, m, k;
struct muchie
{
int x, y, c;
};
muchie a[DIM];
int t[DIM], cost;
int h[DIM];
vector<pair<int, int> > M;
bool Pred(muchie a, muchie b)
{
return a.c < b.c;
}
int main()
{
Read();
Kruskal();
Write();
return 0;
}
void Read()
{
fin >> n >> m;
M.resize(n+1);
int x, y,c;
for(int i = 1; i <= m; ++i)
{
if( i <= n)
t[i] = i;
fin >> x >> y >> c;
a[i].c = c;
a[i].x = x;
a[i].y = y;
}
}
void Kruskal()
{
sort(a + 1, a + m + 1, Pred);
for(int i = 1; i <= m && k < n-1; ++i)
{
int v1 = Find( a[i].x );
int v2 = Find( a[i].y );
if( v1 != v2)
{
M[++k] = make_pair( a[i].x, a[i].y);
cost += a[i].c;
Union(v1, v2);
}
}
}
int Find(int x)
{
if( t[x] != x )
t[x] = Find( t[x] );
return t[x];
}
void Union(int x, int y)
{
if( h[x] > h[y] )
t[y] = x;
else
{
t[x] = y;
if( h[x] == h[y] )
h[y] += 1;
}
}
void Write()
{
fout << cost << '\n' << n - 1 << '\n';
for(int i = 1; i <= n-1; ++i)
fout << M[i].first << " " << M[i].second << '\n';
}