Cod sursa(job #674552)

Utilizator Dr.OptixCristian Dinu Dr.Optix Data 6 februarie 2012 15:14:45
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <stdio.h>
#include <algorithm>

using namespace std;

struct Node {
	int rank;
	int father;
};

struct Edge {
	int cost;
	int x;
	int y;
};

void init_forest(int node, Node* forest) {
	forest[node].rank = 0;
	forest[node].father = node;
}

int find_root(int node, Node* forest) {
	if (forest[node].father != node) {
		forest[node].father = find_root(forest[node].father, forest);
	}
	return forest[node].father;		
}

void union_trees(int node_a, int node_b, Node* forest) {
	int x_root = find_root(node_a, forest);
	int y_root = find_root(node_b, forest);
	
	if (x_root == y_root) {
		return;
	}
	
	if (forest[x_root].rank < forest[y_root].rank) {
		forest[x_root].father = y_root;
	} else if (forest[x_root].rank > forest[y_root].rank) {
		forest[y_root].father = x_root;
	} else {
		forest[y_root].father = x_root;
		forest[y_root].rank += 1;
	}
}

int edge_cmp_func(Edge x, Edge y) {
	return x.cost < y.cost;
}

int main(int argc, char** argv) {
	int n, e;
	Node forest[200001];
	Edge edges[400001];
	
	FILE* fin = fopen("apm.in", "r");
	FILE* fout = fopen("apm.out","w");
	
	fscanf(fin, "%d%d", &n, &e);
	for (int i = 0; i < e; ++i) {
		fscanf(fin, "%d %d %d", &edges[i].x, &edges[i].y, &edges[i].cost);
	}
	fclose(fin);
	
	for (int i = 0; i < n; ++i) {
		init_forest(i, forest);
	}
	
	sort(edges, edges + e, edge_cmp_func);
	
	int answear = 0, pos = 0;
	Edge answear_edges[400001];
	
	for (int i = 0; i < e; ++i) {
		if (find_root(edges[i].x, forest) != find_root(edges[i].y, forest)) {
			union_trees(edges[i].x, edges[i].y, forest);
			answear += edges[i].cost;
			answear_edges[pos++] = edges[i];
		}
	}

	fprintf(fout, "%d\n%d\n", answear, pos);
	for (int i = 0; i < pos; ++i) {
		fprintf(fout, "%d %d\n", answear_edges[i].x, answear_edges[i].y);
	}
	fclose(fout);
	
	return 0;
}