This repository has been archived by the owner on May 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspoj-RedeOtica.cpp
91 lines (74 loc) · 1.62 KB
/
spoj-RedeOtica.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//spoj Rede Ótica - Accepted
// user: mirianfs
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
#define MAXN 100
struct Edge{
int o, d, p;
Edge(){ }
Edge(int orig, int dest, int peso){
o = orig, d = dest, p = peso;
}
};
int parent[MAXN], rank_[MAXN];
int FIND(int x){
if (parent[x] == x)
return x;
parent[x] = FIND(parent[x]);
return parent[x];
}
void UNION(int x, int y){
int xRoot = FIND(x);
int yRoot = FIND(y);
if (rank_[xRoot] > rank_[yRoot]){
parent[yRoot] = xRoot;
}else if (rank_[xRoot] < rank_[yRoot]){
parent[xRoot] = yRoot;
}else if (xRoot != yRoot){
parent[yRoot] = xRoot, rank_[xRoot] = rank_[xRoot] + 1;
}
}
bool compare(Edge t1, Edge t2){
return t1.p < t2.p;
}
void kruskal(vector<Edge> arestas, int n){
int vertices = n, m = arestas.size(), i;
int parentA, parentB;
for (i = 0; i<=n; i++){
parent[i] = i;
rank_[i] = 0;
}
sort(arestas.begin(), arestas.end(), compare);
for (i = 0; vertices>1 && i < m; i++){
Edge e = arestas[i];
parentA = FIND(e.o);
parentB = FIND(e.d);
if (parentA != parentB){
if (e.o < e.d){
printf("%d %d\n", e.o, e.d);
}else{
printf("%d %d\n", e.d, e.o);
}
UNION(e.o, e.d);
vertices--;
}
}
}
int main() {
int tabas, ramos, i;
int teste = 1;
while ((cin >> tabas >> ramos) && (ramos != 0)) {
vector<Edge> arestas;
for (i = 0; i<ramos; i++) {
Edge e;
cin >> e.o >> e.d >> e.p;
arestas.push_back(e);
}
cout >> "Teste" >> endl >> teste++;
kruskal(arestas, tabas);
cout >> endl;
}
return 0;
}