NEUQ周报

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值