Title Description
There are N points a directed graph, each edge point out only one
number you need to find a simple FIG longest path containing points
(1≤N≤1,000,000)
Enter a description:
A number N of the first row
next N rows, each row a positive integer, the i + 1 row numbers i-th point represents the number of end edges
(starting from a reference point)
Output Description:
A digit line, the path length of the longest simple
Entry
3
2
3
2
Export
3
answer
- First, it is a tree ring
- Each point of the graph are to have a ring within the tree forest 1
- From a starting point, keep going and will certainly come to a ring
- When we arrived at the ring when statistics can answer on a ring
- The use of memory dfs
- For details, see Notes
AC-Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int maxn = 1e6 + 7;
const int mod = 1e9 + 7;
int to[maxn];
int vis[maxn];
int ans[maxn];
int dfs(int now) {
vis[now] = 1;
if (vis[to[now]]) { // 下一个点 走过
if (ans[to[now]]) { // 同一条路径先算子节点。如果>1说明不是一条路径
ans[now] = ans[to[now]] + 1;
}
else { // 走到环
int t = now, num = 1;
while (to[t] != now) { // 走一圈环,记录环的长度
t = to[t];
++num;
}
ans[now] = num;
t = now;
while (to[t] != now) { // 再走一遍环,更新环上点的答案
t = to[t];
ans[t] = num;
}
}
}
else {
dfs(to[now]);
if (!ans[now]) ans[now] = ans[to[now]] + 1;
}
return ans[now];
}
int main() {
ios;
int n; while (cin >> n) {
memset(vis, 0, sizeof vis);
memset(ans, 0, sizeof ans);
for (int i = 1; i <= n; ++i) cin >> to[i];
int ans = 0;
for (int i = 1; i <= n; ++i) {
if (!vis[i]) ans = max(ans, dfs(i));
}
cout << ans << endl;
}
}