洛谷B3862:图的遍历(简单版)← 邻接表

​【题目来源】
https://www.luogu.com.cn/problem/B3862

【题目描述】
给出 N 个点,M 条边的有向图,对于每个点 v,A(v) 表示从点 v 出发,能到达的编号最大的点。

【输入格式】
第 1 行 2 个整数N,M,表示点数和边数。
接下来 M 行,每行 2 个整数 Ui,Vi,表示边(Ui, Vi)。点用 1, 2, ..., N 编号。

【输出格式】
一行 N 个整数 A(1), A(2), ..., A(N)。

【数据范围】
对于 100% 的数据,1≤N,M≤10^3。

【输入样例】
4 3
1 2
2 4
4 3

【输出样例】
4 4 3 4

【算法分析】
● 本题的"链式前向星"实现,详见:https://blog.csdn.net/hnjzsyjyj/article/details/147341814

【算法代码】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

const int N=1e5 + 5;
vector<int> g[N];
int mx[N]; //max node-number reached by node i.
int n,m;

void dfs(int u,int v) {
    mx[v]=u;
    for(int x:g[v]) {
        if(mx[x]==0) dfs(u,x);
    }
}

int main() {
    cin>>n>>m;
    for(int i=0; i<m; i++) {
        int x,y;
        cin>>x>>y;
        g[y].push_back(x); //y →x
    }

    for(int i=n; i>=1; i--) {
        if(mx[i]==0) dfs(i,i);
    }

    for(int i=1; i<=n; i++) {
        cout<<mx[i]<<" ";
    }

    return 0;
}

/*
in:
4 3
1 2
2 4
4 3

out:
4 4 3 4
*/

【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/147341814
https://blog.csdn.net/hnjzsyjyj/article/details/139369904
https://blog.csdn.net/hnjzsyjyj/article/details/147326357
https://blog.csdn.net/hnjzsyjyj/article/details/147333181
https://www.acwing.com/solution/content/3999/

相关推荐
星马梦缘2 天前
算法设计与分析 作业二 答案与解析
算法·图论·dfs·bfs·floyd-warshall·bellman_ford·多源最短路
westdata-Tm2 天前
洛谷P1219 [USACO1.5] 八皇后 Checker Challenge
算法·深度优先·dfs
hnjzsyjyj4 天前
洛谷 B3622:枚举子集(递归实现指数型枚举)← DFS
数据结构·dfs
hnjzsyjyj6 天前
全排列问题DFS实现执行示意图
数据结构·dfs
XLYcmy6 天前
2026游戏安全技术竞赛-PC客户端安全-初赛 求解起点到终点的最短路径
windows·python·网络安全·dfs·bfs·游戏安全·曼哈顿距离
Tisfy11 天前
LeetCode 1722.执行交换操作后的最小汉明距离:连通图
算法·leetcode·dfs·题解·深度优先搜索·连通图
承渊政道13 天前
【递归、搜索与回溯算法】(floodfill算法:从不会做矩阵题,到真正掌握搜索扩散思想)
数据结构·c++·算法·leetcode·矩阵·dfs·bfs
进击的荆棘14 天前
递归、搜索与回溯——二叉树中的深搜
数据结构·c++·算法·leetcode·深度优先·dfs
进击的荆棘14 天前
递归、搜索与回溯——回溯
数据结构·c++·算法·leetcode·dfs