Pagini recente » Cod sursa (job #1729368) | Cod sursa (job #779935) | Cod sursa (job #1359153) | Cod sursa (job #482590) | Cod sursa (job #2174456)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int x, y, w;
bool operator < (const Edge& a) const
{
return w < a.w;
}
};
using VI = vector<int>;
using VE = vector<Edge>;
int n, m, cost;
VE G, arb;
VI t, h;
void Read();
void Kruskal();
int Find(int x);
void Union(int x, int y);
void Write();
int main()
{
Read();
Kruskal();
Write();
}
int Find(int x)
{
if (x == t[x]) return x;
return t[x] = Find(t[x]);
}
void Union(int x, int y)
{
if (h[x] < h[y])
t[x] = y;
else
{
t[y] = x;
if (h[x] == h[y])
h[x]++;
}
}
void Kruskal()
{
sort(G.begin(), G.end());
int x, y, c1, c2;
for (const Edge& e : G)
{
x = e.x;
y = e.y;
c1 = Find(x);
c2 = Find(y);
if (c1 == c2)
continue;
cost += e.w;
Union(c1, c2);
arb.push_back(e);
}
}
void Write()
{
ofstream fout("apm.out");
fout << cost << '\n' << n - 1 << '\n';
for (const Edge& e : arb)
fout << e.x << ' ' << e.y << '\n';
fout.close();
}
void Read()
{
ifstream fin("apm.in");
fin >> n >> m;
t = h = VI(n + 1);
for (int i = 1; i <= n; i++)
t[i] = i, h[i] = 1;
int x, y, w;
while (m--)
{
fin >> x >> y >> w;
G.push_back({x, y, w});
}
fin.close();
}