Pagini recente » Cod sursa (job #2898447) | Cod sursa (job #564637) | Cod sursa (job #1162455) | Cod sursa (job #1216128) | Cod sursa (job #1399014)
#include <fstream>
#include <vector>
#include <algorithm>
#define mp make_pair
using namespace std;
ifstream is("apm.in");
ofstream os("apm.out");
int n, m, answ;
vector<int> t, h;
vector<pair<int, int> > w;
vector<pair<int, pair<int, int> > > e;
void Read();
void Union(int x, int y);
int Find(int x);
int main()
{
Read();
sort(e.begin(), e.end());
t = h = vector<int>(n + 1);
for ( int i = 1; i <= n; ++i )
t[i] = i;
int x, y, xx, yy;
for ( size_t i = 0; i < e.size() && w.size() < n - 1; ++i )
{
x = e[i].second.first;
y = e[i].second.second;
xx = Find(x);
yy = Find(y);
if ( xx != yy )
{
Union(xx, yy);
w.push_back(mp(x, y));
answ += e[i].first;
}
}
os << answ << "\n" << w.size() << "\n";
for ( int i = 0; i < n - 1; ++i )
os << w[i].first << " " << w[i].second << "\n";
is.close();
os.close();
return 0;
}
void Union(int x, int y)
{
if ( h[x] < h[y] )
t[x] = y;
else
{
t[y] = x;
if ( h[x] == h[y] )
++h[x];
}
}
int Find(int x)
{
if ( x == t[x] )
return x;
return t[x] = Find(t[x]);
}
void Read()
{
is >> n >> m;
int n1, n2, cost;
for ( int i = 1; i <= m; ++i )
{
is >> n1 >> n2 >> cost;
e.push_back(mp(cost, mp(n1, n2)));
}
}