Pagini recente » Cod sursa (job #2702369) | Cod sursa (job #2274476) | Cod sursa (job #492857) | Cod sursa (job #2340300) | Cod sursa (job #1420540)
// Kruskal - O(MlogM+Mlog*N)
#include <fstream>
#include <vector>
#include <algorithm>
#define Nmax 200099
#define pb push_back
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct edge{
int x,y,c;
edge(int x = 0, int y = 0, int c = 0) {
this->x = x;
this->y = y;
this->c = c;
}
};
struct cmp{
bool operator()(const edge& A, const edge& B) {
return A.c < B.c;
}
};
int N, M, T[Nmax], costAPM;
vector < edge > E;
vector < int > sol;
int gr(const int& x)
{
if(T[x] != x) {
T[x] = gr(T[x]);
}
return T[x];
}
void reunion(const int& x, const int& y)
{
T[gr(x)] = gr(y);
}
void Kruskal()
{
sort(E.begin(), E.end(), cmp());
for(int i = 1; i <= N; ++i) {
T[i] = i;
}
for(int i = 0; i < M && (int) sol.size() != N-1; ++i) {
if(gr(E[i].x) != gr(E[i].y)) {
costAPM += E[i].c;
sol.push_back(i);
reunion(E[i].x, E[i].y);
}
}
}
int main()
{
f >> N >> M;
for(int i = 1; i <= M; ++i) {
int x, y, c;
f >> x >> y >> c;
E.pb(edge(x, y, c));
}
Kruskal();
g<< costAPM << '\n';
g<< sol.size() << '\n';
for (vector<int>::iterator it = sol.begin(); it != sol.end(); it++) {
g<< E[*it].x << ' ' << E[*it].y << '\n';
}
f.close();g.close();
return 0;
}