Pagini recente » Cod sursa (job #227268) | Cod sursa (job #331804) | Cod sursa (job #896934) | Cod sursa (job #3197529) | Cod sursa (job #1630781)
#include <fstream>
#include <vector>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
ifstream is("apm.in");
ofstream os("apm.out");
using VI = vector<int>;
using VP = vector<pair<int, int>>;
using VPP = vector<pair<int, pair<int, int>>>;
int n, m, cnt, answ;
VI t, h;
VP e;
VPP g;
void Read();
void Write();
void Union(int x, int y);
int Find(int x);
int main()
{
Read();
sort(g.begin(), g.end());
int x, y, xx, yy;
t = h = VI(n + 1);
for ( int i = 1; i <= n; ++i )
t[i] = i;
for ( VPP::iterator it = g.begin(); it != g.end() && cnt < n - 1; ++it )
{
x = it->second.first;
y = it->second.second;
if ( ( xx = Find(x) ) != ( yy = Find(y) ) )
{
++cnt;
answ += it->first;
e.push_back(make_pair(x, y));
Union(xx, yy);
}
}
Write();
is.close();
os.close();
return 0;
}
void Union(int x, int y)
{
if ( h[x] > h[y] )
t[y] = x;
else
{
t[x] = y;
++h[y];
}
}
int Find(int x)
{
if ( x == t[x] )
return x;
return t[x] = Find(t[x]);
}
void Read()
{
is >> n >> m;
g = VPP(n + 1);
int a, b, c;
while ( m-- )
{
is >> a >> b >> c;
g.push_back(make_pair(c, make_pair(a, b)));
}
}
void Write()
{
os << answ << "\n" << n - 1 << "\n";
for ( const auto &x : e )
os << x.first << " " << x.second << "\n";
}