-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprim.c
103 lines (80 loc) · 1.49 KB
/
prim.c
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
92
93
94
95
96
97
98
99
100
101
102
103
#include<stdio.h>
#include<stdlib.h>
#define N 100
static int stack[N];
static int last, first;
int unstack(int n, int chave[n]){
int menor = 10000, i, j;
i = first;
while(i < last && chave[i] > menor){
i++;
}
int vertice;
vertice = stack[i];
if(i != first && i != last){
for ( j = i; j < last; j++) {
stack[j] = stack[j + 1];
}
last--;
}
if(i == first) first++;
if(i == last) last--;
return vertice;
}
void stackup(int value){
stack[last++] = value;
}
int isvoid(void){
if(last == first) return 0;
return 1;
//return p >= u;
}
void createstack(void){
first = last = 0;
}
int Estack(int n){
int i;
for ( i = first; i < last; i++) {
if(stack[i] == n) return 1;
}
return 0;
}
void prim(int n, int matrix[n][n]){
int pai[n], chave[n], i, u;
for (i = 0; i < n; i++){
pai[i] = -1;
chave[i] = 10000;
}
chave[0] = 0;
createstack();
for ( i = 0; i < n; i++) {
stackup(i);
}
while(isvoid() != 0){
u = unstack(n, chave);
for ( i = 0; i < n; i++) {
if (matrix[u][i] != 0) {
if(Estack(i) == 1 && matrix[u][i] < chave[i]){
pai[i] = u;
chave[i] = matrix[u][i];
}
}
}
}
printf("0: -\n");
for (i = 1; i < n; i++) {
printf("%d: %d\n",i,pai[i]);
}
}
int main(void) {
int i, j, n;
scanf(" %d",&n);
int adj_matrix[n][n];
for(i=0;i<n;i++){
for(j=0;j<n;j++){
scanf(" %d",&adj_matrix[i][j]);
}
}
prim(n, adj_matrix);
return 0;
}