Pagini recente » Cod sursa (job #3304428) | Cod sursa (job #3353659) | Cod sursa (job #530824) | Cod sursa (job #2035534) | Cod sursa (job #3344193)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int NMAX = 2e5 + 2;
int n, m, tata[NMAX], s[NMAX];
vector<tuple<int, int, int>> edges;
int findRoot(int nod)
{
int root = nod;
while(tata[root] != root)
{
root = tata[root];
}
while(tata[nod] != root)
{
int temp = tata[nod];
tata[nod] = root;
nod = temp;
}
return root;
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, cost;
fin >> x >> y >> cost;
edges.push_back({cost, x, y});
}
sort(edges.begin(), edges.end());
vector<pair<int, int>> sol;
// DSU
for(int i = 1; i <= n; i++)
{
tata[i] = i;
s[i] = 1;
}
int sum = 0;
for(auto [cost, x, y]: edges)
{
if(findRoot(x) != findRoot(y))
{
sum += cost;
sol.push_back({x, y});
cout << x << " " << y << " cu root " << findRoot(x) << " " << findRoot(y) << "\n";
if(s[x] <= s[y])
{
tata[findRoot(x)] = findRoot(y);
s[y] += s[x];
}
else{
tata[findRoot(y)] = findRoot(x);
s[x] += s[y];
}
}
}
fout << sum << "\n" << n - 1 << "\n";
for(auto [x, y]: sol)
{
fout << x << " " << y << "\n";
}
return 0;
}