
fibra otica
By: a guest on
May 9th, 2012 | syntax:
C++ | size: 1.47 KB | hits: 20 | expires: Never
#include <cstdio>
#include <algorithm>
#include <vector>
#define MAX_EDGES 150000
#define MAX_NODES 1000
using namespace std;
struct Edge {
int u, v, cost;
void set (int x, int y, int custo) {
u = x;
v = y;
cost = custo;
}
bool operator <(const struct Edge &lhs) const {
return cost < lhs.cost;
}
void imprimir () {
printf("%d %d\n", u, v);
}
};
Edge aresta[MAX_EDGES];
int rep[MAX_NODES];
vector <Edge> agpm;
int n, m, u, v, c;
bool read () {
scanf("%d %d", &n, &m);
if(!n) return false;
for (int i = 1; i <= n; i++) {
rep[i] = i;
}
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &u, &v, &c);
if (u < v) aresta[i].set(u, v, c);
else aresta[i].set(v, u, c);
}
return true;
}
int find (int pos) {
if (rep[pos] == pos) return pos;
rep[pos] = find(rep[pos]);
return rep[pos];
}
bool uniao (int a, int b) {
int temp1 = find(a);
int temp2 = find(b);
if (temp1 != temp2) {
rep[temp1] = temp2;
return true;
}
return false;
}
int qtd;
void kruskal () {
sort (aresta, aresta + m);
for (int i = 0; i < m && qtd < n; i++) {
if (uniao(aresta[i].u, aresta[i].v)) {
agpm.push_back(aresta[i]);
qtd++;
}
}
}
int testes = 1;
void process () {
qtd = 1;
printf("Teste %d\n", testes++);
agpm.clear();
kruskal();
for (int i = 0; i < qtd - 1; i++) {
agpm[i].imprimir();
}
printf("\n");
}
int main () {
while (read()) {
process();
}
return 0;
}