Pagini recente » Cod sursa (job #2954075) | Cod sursa (job #2716045) | Cod sursa (job #2379375) | Rating ant cc (cca.new) | Cod sursa (job #2171796)
#include<cstdio>
#include<vector>
#include<algorithm>
#define MAX_N 200000
using namespace std;
struct edge {
int x, y, cost;
};
edge v[MAX_N + 1];
vector<pair<int,int > >apm;
int p[MAX_N + 1], h[MAX_N + 1], n, m, minCost, apmSize;
void readGraph() {
FILE* fin = fopen("apm.in","r");
fscanf(fin,"%d%d",&n,&m);
for(int i = 0; i < m; i++)
fscanf(fin,"%d%d%d",&v[i].x,&v[i].y,&v[i].cost);
fclose(fin);
}
inline int cmp(edge a, edge b) {
return a.cost < b.cost;
}
void Init(int n) {
for(int i = 1; i <= n; i++) {
p[i] = i;
h[i] = 1;
}
}
inline int Find(int x) {
int r, aux;
r = x;
while(p[r] != r)
r = p[r];
while(p[x] != r) {
aux = p[x];
p[x] = r;
x = aux;
}
return r;
}
inline void Union(int x, int y, int i) {
int rx, ry;
rx = Find(x);
ry = Find(y);
if(rx != ry) {
minCost += v[i].cost;
apm.push_back(make_pair(x,y));
apmSize++;
if(h[rx] < h[ry])
p[rx] = ry;
else if(h[rx] > h[ry])
p[ry] = rx;
else {
p[rx] = ry;
h[ry]++;
}
}
}
void Kruskal() {
apmSize = minCost = 0;
sort(v,v+m,cmp);
Init(n);
for(int i = 0; apmSize < n-1; i++)
Union(v[i].x,v[i].y,i);
}
void printAPM() {
vector< pair<int, int> > ::iterator it;
FILE* fout = fopen("apm.out","w");
fprintf(fout,"%d\n%d\n",minCost,apmSize);
for(it = apm.begin(); it != apm.end(); it++)
fprintf(fout,"%d %d\n",(*it).first,(*it).second);
fclose(fout);
}
int main() {
readGraph();
Kruskal();
printAPM();
return 0;
}