洛谷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/

相关推荐
浅念-1 天前
LeetCode 回溯算法题——综合练习
数据结构·c++·算法·leetcode·职场和发展·深度优先·dfs
浅念-8 天前
LeetCode回溯算法从入门到精通完整解析
开发语言·数据结构·c++·算法·leetcode·dfs·深度优先遍历
YL200404269 天前
048路径总和III
数据结构·dfs
进击的荆棘10 天前
递归、搜索与回溯——综合(下)
c++·算法·leetcode·深度优先·dfs
tiandyoin10 天前
IPCONFIG重置网络
网络·ip·dfs·dns·vpn·cmd
hnjzsyjyj14 天前
洛谷 P1305:新二叉树 ← DFS + 字符索引数组 + map
dfs·stl map·字符索引数组
hnjzsyjyj15 天前
洛谷 P1305:新二叉树 ← DFS
数据结构·dfs
进击的荆棘17 天前
递归、搜索与回溯——综合(上)
c++·算法·leetcode·深度优先·dfs
多喝开水少熬夜21 天前
dfs思路回溯
算法·深度优先·dfs