P3916 图的遍历 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
代码
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表中的节点
typedef struct Node {
int vertex;
struct Node* next;
} Node;
// 定义图的邻接表
typedef struct {
Node** adjacency_list;
int* max_reachable; // 存储每个节点能够到达的最大编号节点
} Graph;
// 添加边到邻接表
void addEdge(Graph* graph, int src, int dest) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = dest;
newNode->next = graph->adjacency_list[src];
graph->adjacency_list[src] = newNode;
}
// 递归实现深度优先搜索
void DFS(Graph* graph, int vertex, int current_max) {
Node* temp = graph->adjacency_list[vertex];
while (temp != NULL) {
if (current_max < temp->vertex) {
current_max = temp->vertex;
}
DFS(graph, temp->vertex, current_max);
temp = temp->next;
}
}
// 执行深度优先搜索并更新每个节点的最大可达节点
void findMaxReachable(Graph* graph, int N) {
for (int i = 1; i <= N; ++i) {
graph->max_reachable[i] = i; // 初始值设为节点本身
DFS(graph, i, i);
}
}
// 打印结果
void printResult(Graph* graph, int N) {
for (int i = 1; i <= N; ++i) {
printf("%d ", graph->max_reachable[i]);
}
printf("\n");
}
int main() {
int N, M;
scanf("%d %d", &N, &M);
// 初始化图
Graph graph;
graph.adjacency_list = (Node**)malloc((N + 1) * sizeof(Node*));
graph.max_reachable = (int*)malloc((N + 1) * sizeof(int));
for (int i = 1; i <= N; ++i) {
graph.adjacency_list[i] = NULL;
}
// 读取边信息并构建图
for (int i = 0; i < M; ++i) {
int Ui, Vi;
scanf("%d %d", &Ui, &Vi);
addEdge(&graph, Ui, Vi);
}
// 执行深度优先搜索
findMaxReachable(&graph, N);
// 输出结果
printResult(&graph, N);
// 释放内存
for (int i = 1; i <= N; ++i) {
Node* temp = graph.adjacency_list[i];
while (temp != NULL) {
Node* next = temp->next;
free(temp);
temp = next;
}
}
free(graph.adjacency_list);
free(graph.max_reachable);
return 0;
}