蔡子经数据结构7.14

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


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXN 100
typedef struct edge
{
int u,v,cost;
} edge;
int par[MAXN];
int rank[MAXN];

void init(int n)
{
for(int i = 0; i < n; ++i)
{
par[i] = i;
rank[i] = 0;
}
}

int find(int x)
{
if(par[x] == x)
return x;
else
return par[x] = find(par[x]);
}

void unite(int x, int y)
{
x = find(x);
y = find(y);
if(x == y) return;
if(rank[x] < rank[y])
par[x] = y;
else
{
par[y] = x;
if(rank[x] == rank[y]) rank[x]++;
}
}

int same(int x, int y)
{
return find(x) == find(y);
}

int cmp(const void* a, const void* b)
{
return ((edge*)a)->cost - ((edge*)b)->cost;
}
edge es[MAXN];
int V,E;//顶点个数和边的个数

int kruskal()
{
qsort(es, E, sizeof(edge), cmp);
init(V);
int res = 0;
for(int i = 0; i < E; ++i)
{
edge e = es[i];
if(!same(e.u, e.v))
{
unite(e.u, e.v);
res += e.cost;
}
}
return res;
}

int main()
{
return 0;
}