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