Pagini recente » Cod sursa (job #357780) | Cod sursa (job #1601966) | Cod sursa (job #2048656) | Cod sursa (job #2068925) | Cod sursa (job #704017)
Cod sursa(job #704017)
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;
int n, m;
int k, cost;
int t[400001], h[400001];
struct muchii
{
int x, y, c;
} a[400001];
vector< pair<int , int> > M;
bool Pred(muchii a, muchii b)
{
return a.c < b.c;
}
void Read();
void APM();
void Write();
int Find(int );
void Union(int, int);
int main()
{
Read();
APM();
Write();
return 0;
}
void Read()
{
ifstream fin("apm.in");
fin >> n >> m;
M.resize(m+1);
int x, y, c;
for(int i = 1; i <= m; ++i)
{
if( i <= n ) t[i] = i;
fin >> x >> y >> c;
a[i].x = x;
a[i].y = y;
a[i].c = c;
}
}
void APM()
{
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 )
{
cost += a[i].c;
M[++k] = make_pair(a[i].x, a[i].y);
Union(v1, v2);
}
}
}
int Find(int x)
{
if( x != t[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];
}
}
void Write()
{
ofstream fout("apm.out");
fout << cost <<"\n" << k << "\n";
for(int i = 1; i <= n-1; ++i)
fout << M[i].first << " "<<M[i].second << "\n";
fout.close();
}