Pagini recente » Cod sursa (job #838153) | Cod sursa (job #1682838) | Cod sursa (job #302851) | Cod sursa (job #561418) | Cod sursa (job #2344168)
#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;
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)
{
int r = k, y=0;
while(father[r]!=r) r=father[r];
while(father[k]!=k)
{
y=father[k];
father[k]=r;
k=y;
}
return r;
}
int main()
{
int a, i = 1, b;
long long y = 0;
fin >> n >> m;
f();
while(fin >> graphs[i].nod1 >> graphs[i].nod2 >> graphs[i].cost)
i++;
sort(graphs + 1, graphs + m + 1, compare);
i = 1;
while(i <= m)
{
a = Radacina(graphs[i].nod1);
b = Radacina(graphs[i].nod2);
if(a != b)
solutii[x] = graphs[i], father[a] = b, y+=graphs[i].cost, x++;
i++;
}
fout << y << '\n';
fout << x << '\n';
for(i = 0; i < x; i++)
fout << solutii[i].nod1 << " " << solutii[i].nod2 << '\n';
return 0;
}