c语言 最小二叉树 内容:(1)由给定的顶点和边的信息构造图的邻接矩阵存储; (2)对该图进行深度优先搜索,输出搜索得到的结点序列; 以邻接表作存储结构,用克鲁斯卡尔算法构造最小生成树。
时间: 2024-03-13 20:45:01 浏览: 62
最小生成树有很多种生成方法,主要有普利姆算法和克鲁斯卡尔算法,通过C语言easyx图形库实现
5星 · 资源好评率100%
抱歉,我之前的回答有误,最小二叉树其实是指最小生成树(Minimum Spanning Tree),以下是C语言下的实现。
1. 构造图的邻接矩阵存储
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
int graph[MAX_VERTICES][MAX_VERTICES];
void add_edge(int u, int v, int weight) {
graph[u][v] = weight;
graph[v][u] = weight;
}
int main() {
int vertices, edges;
scanf("%d%d", &vertices, &edges);
for (int i = 0; i < edges; i++) {
int u, v, weight;
scanf("%d%d%d", &u, &v, &weight);
add_edge(u, v, weight);
}
return 0;
}
```
2. 深度优先搜索
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100
int graph[MAX_VERTICES][MAX_VERTICES];
bool visited[MAX_VERTICES];
void dfs(int u, int vertices) {
visited[u] = true;
printf("%d ", u);
for (int v = 0; v < vertices; v++) {
if (graph[u][v] && !visited[v]) {
dfs(v, vertices);
}
}
}
int main() {
int vertices, edges;
scanf("%d%d", &vertices, &edges);
for (int i = 0; i < edges; i++) {
int u, v, weight;
scanf("%d%d%d", &u, &v, &weight);
add_edge(u, v, weight);
}
dfs(0, vertices);
return 0;
}
```
3. 克鲁斯卡尔算法构造最小生成树
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
#define MAX_EDGES 100
struct edge {
int u, v;
int weight;
};
struct edge edges[MAX_EDGES];
int parent[MAX_VERTICES];
int rank[MAX_VERTICES];
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union_set(int x, int y) {
int root_x = find(x);
int root_y = find(y);
if (root_x == root_y) {
return;
}
if (rank[root_x] < rank[root_y]) {
parent[root_x] = root_y;
} else if (rank[root_x] > rank[root_y]) {
parent[root_y] = root_x;
} else {
parent[root_x] = root_y;
rank[root_y]++;
}
}
int cmp(const void *a, const void *b) {
return ((struct edge *)a)->weight - ((struct edge *)b)->weight;
}
int main() {
int vertices, edges_num;
scanf("%d%d", &vertices, &edges_num);
for (int i = 0; i < edges_num; i++) {
int u, v, weight;
scanf("%d%d%d", &u, &v, &weight);
edges[i].u = u;
edges[i].v = v;
edges[i].weight = weight;
}
qsort(edges, edges_num, sizeof(struct edge), cmp);
for (int i = 0; i < vertices; i++) {
parent[i] = i;
rank[i] = 0;
}
int mst_edges = 0;
for (int i = 0; i < edges_num; i++) {
if (find(edges[i].u) != find(edges[i].v)) {
union_set(edges[i].u, edges[i].v);
mst_edges++;
printf("%d %d %d\n", edges[i].u, edges[i].v, edges[i].weight);
if (mst_edges == vertices - 1) {
break;
}
}
}
return 0;
}
```
阅读全文