Pagini recente » Cod sursa (job #2832782) | Cod sursa (job #1013594) | Cod sursa (job #290194) | Cod sursa (job #2978663) | Cod sursa (job #3136661)
#include <fstream>
#include <algorithm>
using namespace std;
const int N = 2e5;
const int M = 4e5;
struct muchie
{
int x, y, c;
};
muchie e[M];
bool sel[M];
int t[N+1], nr[N+1], n;
bool cmp(muchie e1, muchie e2)
{
return (e1.c < e2.c);
}
int radacina(int x)
{
if (t[x] == 0)
{
return x;
}
t[x] = radacina(t[x]);
return t[x];
}
void reuniune(int x, int y)
{
int rx = radacina(x);
int ry = radacina(y);
if (nr[rx] < nr[ry])
{
t[rx] = ry;
nr[ry] += nr[rx];
}
else
{
t[ry] = rx;
nr[rx] += nr[ry];
}
}
bool interogare(int x, int y)
{
return (radacina(x) == radacina(y));
}
int main()
{
ifstream in("apm.in");
ofstream out("apm.out");
int m;
in >> n >> m;
for (int i = 0; i < m; i++)
{
in >> e[i].x >> e[i].y >> e[i].c;
}
sort(e, e + m, cmp);
for (int i = 1; i <= n; i++)
{
nr[i] = 1;
}
int n_e = 0, i = 0, total = 0;
while (n_e < n - 1)
{
if (!interogare(e[i].x, e[i].y))
{
reuniune(e[i].x, e[i].y);
total += e[i].c;
sel[i] = true;
n_e++;
}
i++;
}
out << total << "\n" << n - 1 << "\n";
for (int i = 0; i < m; i++)
{
if (sel[i])
{
out << e[i].x << " " << e[i].y << "\n";
}
}
in.close();
out.close();
return 0;
}