Files
Data-Structure/Algorithm/DP-DynamicProgramming/P3916 图的遍历.cpp
2025-09-21 12:21:50 +08:00

62 lines
1.3 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <iostream>
#include <vector>
using namespace std;
int main(){
//dp只能O(n3)这里最好用bfs或者dfs
int v, e;
cin >> v >> e;
//vector<vector<int>> adj(v, vector<int>());
vector<vector<bool>> dp(v, vector<bool>(v, false));
for(int i = 0; i < e; i++){
int a, b;
cin >> a >> b;
//adj[a - 1].push_back(b - 1);
//adj[b - 1].push_back(a - 1);
dp[a - 1][b - 1] = true;
}
//考虑dp[i][j] : 两个点是否连通采取插入k的方式解决
for (int i = 0; i < v; i++) dp[i][i] = true; // 自己到自己连通
for(int k = 0; k < v; k++){
for(int i = 0; i < v; i++){
for(int j = 0; j < v; j++){
if(dp[i][j]) continue;
dp[i][j] = dp[i][j] || (dp[i][k] & dp[k][j]);
}
}
}
//bfs
for(int i = 0; i < v; i++) {
vector<bool> visited(v, false);
queue<int> q;
q.push(i);
visited[i] = true;
int mx = i;
while (!q.empty()) {
int curr = q.front();
q.pop();
for (int next : adj[curr]) {
if (!visited[next]) {
visited[next] = true;
q.push(next);
mx = max(mx, next);
}
}
}
cout << mx + 1 << " ";
}
for(int i = 0; i < v; i++){
int mx = -1;
for(int j = 0; j < v; j++){
if(dp[i][j] && mx < j) mx = j;
}
cout << mx + 1 << " ";
}
cout << endl;
return 0;
}