Pagini recente » Cod sursa (job #2305836) | Cod sursa (job #961586) | Cod sursa (job #1994123) | Atasamentele paginii bolt-dogs | Cod sursa (job #2425912)
#include <fstream>
#include <algorithm>
#define MAX 400001
using namespace std;
struct muchie
{
int st;
int dr;
int cost;
}v[MAX];
struct pereche
{
int st;
int dr;
}arbore[MAX];
int daddy[MAX / 2 + 1];
int find_daddy(int nod)
{
if(daddy[nod] == nod)return nod;
return nod = find_daddy(daddy[nod]);
}
bool union_find(int nod1, int nod2)
{
int daddy1 = find_daddy(nod1);
int daddy2 = find_daddy(nod2);
if(daddy1 != daddy2)
{
daddy[daddy1] = daddy2;
return true;
}
return false;
}
bool cmp(muchie a, muchie b)
{
if(a.cost < b.cost)return true;
return false;
}
int main()
{
int n, m, i, j, costMinim = 0, contor = 0;
ifstream fin("apm.in");
ofstream fout("apm.out");
fin >> n >> m;
for(i = 1; i <= m; i++)
{
fin >> v[i].st >> v[i].dr >> v[i].cost;
}
sort(v + 1, v + m + 1, cmp);
for(i = 1; i <= n; i++)daddy[i] = i;
costMinim = contor = 0;
j = 0;
for(i = 1; contor < n - 1 && i <= m; i++)
{
if(union_find(v[i].st, v[i].dr))
{
j++;
arbore[j].st = v[i].st;
arbore[j].dr = v[i].dr;
costMinim += v[i].cost;
contor++;
}
}
fout << costMinim << '\n' << contor << '\n';
for(i = 1; i <= j; i++)fout << arbore[i].st << " " << arbore[i].dr << '\n';
fin.close();
fout.close();
return 0;
}