Pagini recente » Cod sursa (job #879543) | Cod sursa (job #2357730) | Cod sursa (job #1681756) | Cod sursa (job #603492) | Cod sursa (job #1096129)
// Algoritmul lui Kruskal
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int N, M;
int sum, nr;
int X[200002], Y[200002], C[200002], pos[200002];
int T[200002], R[200002];
vector<int> V;
bool cmp(int a, int b)
{
return (C[a] < C[b]);
}
int find(int x)
{
int rad, aux;
for (rad = x; T[rad] != rad; rad = T[rad]);
while (T[rad] != rad)
{
aux = T[x];
T[x] = rad;
x = aux;
}
return rad;
}
void unite(int x, int y)
{
if (R[x] > R[y]) T[y] = x;
else T[x] = y;
if (R[x] == R[y]) ++R[y];
}
int main()
{
fin >> N >> M;
for (int i = 1; i <= M; ++i)
{
fin >> X[i] >> Y[i] >> C[i];
pos[i] = i;
}
sort(pos + 1, pos + M + 1, cmp);
for (int i = 1; i <= N; ++i)
{
T[i] = i;
R[i] = 1;
}
for (int i = 1; i <= M; ++i)
{
int nr1 = find(X[pos[i]]);
int nr2 = find(Y[pos[i]]);
if (nr1 != nr2)
{
++nr;
sum += C[pos[i]];
unite(nr1, nr2);
V.push_back(pos[i]);
}
}
fout << sum << '\n' << nr << '\n';
for (int i = 1; i <= nr; ++i)
fout << X[V[i - 1]] << ' ' << Y[V[i - 1]] << '\n';
fin.close();
fout.close();
return 0;
}