-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinclass-16-1130-minimum-spanning-tree.cpp
More file actions
75 lines (73 loc) · 1.36 KB
/
inclass-16-1130-minimum-spanning-tree.cpp
File metadata and controls
75 lines (73 loc) · 1.36 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <vector>
#include <queue>
using namespace std;
// graph
#define MAX_V 5
#define MAX_E 10
int G[MAX_V][MAX_V];
// disjoint set
int v[MAX_V];
int find(int n) {
if(v[n] == n) return n;
return v[n] = find(v[n]);
}
void merge(int a, int b){
int ra = find(a);
int rb = find(b);
v[ra] = rb;
}
int same(int a, int b) {
return find(a) == find(b);
}
typedef struct {
int a, b, v;
}Edge;
bool cmp(Edge a, Edge b) {
return a.v < b.v;
}
// main
int main() {
memset(G, 0, sizeof(G));
for(int q=0; q<MAX_V; q++) {
v[q] = q;
}
int a, b, c;
printf("original edge\n");
priority_queue<Edge, vector<Edge>, decltype(&cmp)> edge(&cmp);
for(int q=0; q<MAX_E; q++) {
a = b = 0;
while(a == b || G[a][b] != 0) {
a = rand()%MAX_V;
b = rand()%MAX_V;
}
c = rand()%20+1;
G[a][b] = c;
G[b][a] = c;
edge.push({a, b, c});
printf("%d %d %d\n", a, b, c);
}
printf("-----\n");
while(!edge.empty()) {
Edge temp = edge.top();
edge.pop();
if(!same(temp.a, temp.b)) {
G[temp.a][temp.b] *= -1;
G[temp.b][temp.a] *= -1;
merge(temp.a, temp.b);
}
}
printf("connected edge\n");
for(int q=0; q<MAX_V; q++) {
for(int w=q+1; w<MAX_V; w++) {
if(G[q][w] > 0) {
printf("%d %d %d\n", q, w, G[q][w]);
} else if(G[q][w] < 0) {
printf("%d %d [%d]\n", q, w, -G[q][w]);
}
}
}
}