Pagini recente » Cod sursa (job #1009317) | Cod sursa (job #2217575) | Cod sursa (job #2566649) | Cod sursa (job #2438804) | Cod sursa (job #3139698)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
#define NMAX 400005
vector<pair<int, pair<int, int>>> G;
vector<pair<int, int>> muchii;
int tata[NMAX / 2], rang[NMAX / 2];
int radacina(int x)
{
int parinte = x;
while (tata[parinte] != parinte)
parinte = tata[parinte];
while (tata[x] != x)
{
int y = tata[x];
tata[x] = parinte;
x = y;
}
return parinte;
}
void uneste(int x, int y)
{
if (rang[x] > rang[y])
tata[y] = x;
else
tata[x] = y;
if (rang[x] == rang[y])
rang[y]++;
}
int main()
{
int n, m;
fin >> n >> m;
for (int i = 0; i < m; ++i)
{
int x, y, c;
fin >> x >> y >> c;
G.push_back({c, {x, y}});
}
sort(G.begin(), G.end());
for (int i = 1; i <= n; ++i)
{
tata[i] = i;
rang[i] = 1;
}
int total = 0;
for (int i = 0; i < m; ++i)
if (radacina(G[i].second.first) != radacina(G[i].second.second))
{
total += G[i].first;
muchii.push_back({G[i].second.first, G[i].second.second});
uneste(radacina(G[i].second.first), radacina(G[i].second.second));
}
fout << total << '\n';
fout << n - 1 << '\n';
for (auto it : muchii)
fout << it.first << ' ' << it.second << '\n';
return 0;
}