Pagini recente » Cod sursa (job #302420) | Cod sursa (job #1523222) | Cod sursa (job #2393735) | Cod sursa (job #297937) | Cod sursa (job #2977037)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie{
int x, y;
int cost;
int viz = 0;
}muc[200001];
int n, m;
int t[200001];
int h[200001];
void initializare()
{
for(int i = 1; i <= n; ++i)
{
t[i] = i;
h[i] = 1;
}
}
int gasim_tata(int x)
{
int aux = x;
while(t[x] != x)
x = t[x];
while(aux != x)
{
int next = t[aux];
t[aux] = x;
aux = next;
}
return x;
}
void unire(int x, int y)
{
int tata_y = gasim_tata(y);
int tata_x = gasim_tata(x);
if(h[tata_y] < h[tata_x])
{
t[tata_y] = tata_x;
h[tata_y] = h[tata_x];
}
else if(h[tata_x] < h[tata_y])
{
t[tata_x] = tata_y;
h[tata_x] = h[tata_y];
}
else
{
t[tata_x] = tata_y;
h[tata_y]++;
h[tata_x] = h[tata_y];
}
}
bool comp(muchie a, muchie b)
{
return a.cost < b.cost;
}
void citire()
{
fin >> n >> m;
for(int i = 0; i < m; ++i)
fin >> muc[i].x >> muc[i].y >> muc[i].cost;
}
int kruskal()
{
int c = 0;
for(int i = 0; i < m; ++i)
{
if(gasim_tata(muc[i].x) != gasim_tata(muc[i].y))
{
muc[i].viz = 1;
c += muc[i].cost;
unire(muc[i].x, muc[i].y);
}
}
return c;
}
int main()
{
citire();
initializare();
sort(muc, muc + m, comp);
fout << kruskal() << '\n' << n - 1 << '\n';
for(int i = 0; i < m; ++i)
if(muc[i].viz)
fout << muc[i].x << ' ' << muc[i].y << '\n';
return 0;
}