使用dfs找出每一個(gè)節(jié)點(diǎn)的解坎怪。
#include <iostream>
#include <vector>
using namespace std;
vector<int>adj[1001];
bool visited[1001];
int ans;
void dfs(int u) {
if (visited[u]) {
return;
}
visited[u] = true;
ans = max(ans, u);
for (int v : adj[u]) {
dfs(v);
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
for (int i = 1; i <= n; i++) {
ans = 0;
for (int j = 1; j <= n; j++) {
visited[j] = false;
}
dfs(i);
cout << ans << ' ';
}
cout << endl;
return 0;
}