Pagini recente » Cod sursa (job #407098) | Cod sursa (job #1210893) | Cod sursa (job #1852332) | Cod sursa (job #3261769) | Cod sursa (job #2564104)
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m;
long long rez;
struct muchii
{
int x, y, c;
};
muchii muc[400005];
int t[200005], rang[200005];
vector < pair < int , int > > arbore;
bool sortare(muchii m1, muchii m2)
{
return m1.c < m2.c;
}
int Root(int x)
{
if(t[x] == 0)
return x;
else
{
int a = Root(t[x]);
t[x] = a;
return a;
}
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
fin >> muc[i].x >> muc[i].y >> muc[i].c;
}
sort(muc + 1, muc + m + 1, sortare);
/*for(int i = 1; i <= m; i++)
{
cout << muc[i].c << " ";
}*/
int cnt = 0;
for(int i = 1; i <= m && cnt < n; i++)
{
int r1 = Root(muc[i].x), r2 = Root(muc[i].y);
if(r1 != r2)
{
cnt++;
rez += muc[i].c;
arbore.push_back(make_pair(muc[i].x, muc[i].y));
if(rang[r1] > rang[r2])
{
t[r2] = r1;
}
else
{
t[r1] = r2;
if(rang[r1] == rang[r2])
{
rang[r2]++;
}
}
}
}
fout << rez << endl;
fout << arbore.size() << endl;
for(int i = 0; i < arbore.size(); i++)
{
fout << arbore[i].first << " " << arbore[i].second << endl;
}
return 0;
}