Pagini recente » Cod sursa (job #2962611) | Cod sursa (job #2976922) | Cod sursa (job #2558391) | Cod sursa (job #2403017) | Cod sursa (job #3234753)
#include <iostream>
#include <vector>
#include <bitset>
#include <fstream>
#include <algorithm>
using namespace std;
struct muchie
{
int x, y, c;
bool operator < (const muchie& other) const
{
return this->c < other.c;
}
}E[400001];
int t[200001], r[200001], n, m;
void Read()
{
ifstream fin("apm.in");
fin >> n >> m;
for (int i = 1; i <= m; i++)
fin >> E[i].x >> E[i].y >> E[i].c;
}
void Union(int x, int y)
{
if (r[x] > r[y])
t[y] = x;
else {
t[x] = y;
if (r[x] == r[y])
r[y]++;
}
}
int Find(int x)
{
if (t[x] == 0)
return x;
int y = Find(t[x]);
t[x] = y;
return y;
}
void Kruskal()
{
sort(E + 1, E + m + 1);
int totalcost = 0;
vector <pair<int, int> > sol;
for (int i = 1; i <= m; i++)
{
int x = Find(E[i].x);
int y = Find(E[i].y);
if (x != y)
{
Union(x, y);
totalcost += E[i].c;
sol.push_back({ E[i].x, E[i].y });
}
}
ofstream fout("apm.out");
fout << totalcost << "\n" << sol.size() << "\n";
for (auto it : sol)
fout << it.first << " " << it.second << "\n";
}
int main()
{
Read();
Kruskal();
return 0;
}