跳到正文

题解

P3916图的遍历题解

Zero_oler约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟
题目
P3916

版本

  1. v1当前

这题的dfs挺简单的,但是如果打暴力了话会超时,这个时候我就建了一个反向边,代码如下:

C++
#include<bits/stdc++.h>
using namespace std;
int N, M, A[100010];
vector<int> G[100010];

void dfs(int x, int d) {

	A[x] = d;
	for(auto v:G[x])
		if(A[v]==0) dfs(v,d);
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	int u, v;
	cin>>N>>M;
	for(int i=1; i<=M;i++) {
		cin>>u>>v;
		G[v].push_back(u);
	}
	for(int i=N;i>=1;--i){
		if(A[i]==0) dfs(i,i);
	}
	for(int i=1;i<=N;++i) cout<<A[i]<<" ";
	return 0;
}
原文