Pagini recente » Cod sursa (job #990) | Cod sursa (job #966577) | Cod sursa (job #865305) | Cod sursa (job #2260408) | Cod sursa (job #2344159)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("kruskal.in");
ofstream fout("kruskal.out");
struct graf{
int nod1;
int nod2;
int cost;
};
int n, m, nr, father[200002], x, height[200002];
//vector <graf> graphs;
//vector <graf> solutii;
graf graphs[400002], solutii[400002];
bool compare(graf a, graf b)
{
return (a.cost < b.cost);
}
void f()
{
int i;
for(i = 1; i <= n; i++)
father[i] = i;
}
int Radacina(int k)
{
while(father[k] != k)
k = father[k];
return k;
}
void reunite(int a, int b)
{
/*if(height[a] > height[b])
father[b] = a;
else
{
father[a] = b;
if(height[a] == height[b])
height[a]++;
}*/
father[b] = a;
}
int main()
{
int a, i = 0, b, y = 0;
graf var;
fin >> n >> m;
f();
while(fin >> graphs[i].nod1 >> graphs[i].nod2 >> graphs[i].cost)
i++;
sort(graphs, graphs + m, compare);
i = 0;
while(i < m)
{
a = Radacina(graphs[i].nod1);
b = Radacina(graphs[i].nod2);
if(a != b)
solutii[x] = graphs[i], reunite(a, b), y+=graphs[i].cost, x++;
i++;
}
//a = x;
//for(i = 0; i < a; i++)
// nr+=solutii[i].cost;
fout << y << '\n';
fout << x << '\n';
for(i = 0; i < x; i++)
fout << solutii[i].nod1 << " " << solutii[i].nod2 << '\n';
return 0;
}