Pagini recente » Cod sursa (job #2957838) | Cod sursa (job #1202009) | Cod sursa (job #2773725) | Cod sursa (job #1247185) | Cod sursa (job #942031)
Cod sursa(job #942031)
#include <fstream>
#include <vector>
#include <algorithm>
#define MAXN 200011
#define MAXM 400011
using namespace std;
typedef struct
{
int a;
int b;
int c;
int luat;
} mystruct;
int N, M;
mystruct muchii[MAXM];
pair <int, int> point[MAXN];
inline int cmp (mystruct x, mystruct y) {
return x.c < y.c;
}
void Citire ()
{
ifstream fin ("apm.in");
fin >> N >> M;
for (int i = 0; i < M; i++)
fin >> muchii[i].a >> muchii[i].b >> muchii[i].c;
for (int i = 1; i <= N; i++)
point[i].first = i, point[i].second = 1;
sort (muchii, muchii + M, cmp);
}
int Parent (int nod)
{
if (nod == point[nod].first) return nod;
return point[nod].first = Parent (point[nod].first);
}
void Merge_DDS (int x, int y)
{
x = Parent (x);
y = Parent (y);
if (point[x].second > point[y].second) point[y].first = x, point[x].second += point[y].second;
else point[x].first = y, point[y].second += point[x].second;
}
int Kruskal ()
{
int val = 0;
for (int i = 0; i < M; i++)
{
int x = muchii[i].a;
int y = muchii[i].b;
int cost = muchii[i].c;
if (Parent (x) != Parent (y)) Merge_DDS (x, y), val += cost, muchii[i].luat = 1;
}
return val;
}
void Scriere ()
{
ofstream fout ("apm.out");
int a = Kruskal ();
fout << a << "\n" << N - 1 << "\n";
for (int i = 0; i < M; i++)
if (muchii[i].luat) fout << muchii[i].a << " " << muchii[i].b << "\n";
fout.close ();
}
int main ()
{
Citire ();
Scriere ();
return 0;
}