Pagini recente » Cod sursa (job #669080) | Cod sursa (job #2823025) | Cod sursa (job #623765) | Cod sursa (job #636467) | Cod sursa (job #3233407)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 200000
#define M 400000
typedef struct
{
int x, y, c;
} muchie;
muchie e[M];
int t[N+1], nr[N+1];
bool in_apm[M];
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 (rx == ry)
{
return;
}
if (nr[rx] < nr[ry])
{
t[rx] = ry;
nr[ry] += nr[rx];
}
else
{
t[ry] = rx;
nr[rx] += nr[ry];
}
}
bool verif(int x, int y)
{
return (radacina(x) == radacina(y));
}
int cmp(const void* p1, const void* p2)
{
muchie e1 = *(muchie*)p1;
muchie e2 = *(muchie*)p2;
return (e1.c - e2.c);
}
int main()
{
FILE *in, *out;
in = fopen("apm.in", "r");
out = fopen("apm.out", "w");
int n, m;
fscanf(in, "%d%d", &n, &m);
for (int i = 0; i < m; i++)
{
fscanf(in, "%d%d%d", &e[i].x, &e[i].y, &e[i].c);
}
qsort(e, m, sizeof(e[0]), cmp);
for (int i = 1; i <= n; i++)
{
nr[i] = 1;
}
int nrc = n, cost = 0, i = 0;
while (nrc > 1)
{
if (!verif(e[i].x, e[i].y))
{
nrc--;
reuniune(e[i].x, e[i].y);
cost += e[i].c;
in_apm[i] = true;
}
i++;
}
fprintf(out, "%d\n%d\n", cost, n - 1);
for (int i = 0; i < m; i++)
{
if (in_apm[i])
{
fprintf(out, "%d %d\n", e[i].x, e[i].y);
}
}
fclose(in);
fclose(out);
return 0;
}