-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1969A-DFS.cpp
More file actions
72 lines (57 loc) · 1.5 KB
/
Copy path1969A-DFS.cpp
File metadata and controls
72 lines (57 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define umap unordered_map
#define f(i, x, n) for(ll i = x; i < n; i++)
#define endl '\n'
#define optimize() ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
void dfs(const vector<vector<ll>>& g, vector<bool> vis, ll v, ll& dfsDepth);
int main() {
optimize();
ll t;
cin >> t;
while (t--) {
ll n, inp; cin >> n;
vector<vector<ll>> g (n+1);
vector<bool> vis(n+1, 0);
vector <ll> componentLengths;
f (i, 0, n) {
cin >> inp;
g[inp].pb(i+1);
g[i+1].pb(inp);
}
for (auto it : g) {
for (auto kt : it) {
if (!vis[kt]) {
ll dfsDepth = 0;
dfs(g, vis, kt, dfsDepth);
componentLengths.pb(dfsDepth);
}
}
}
sort(componentLengths.begin(), componentLengths.end());
ll mn = componentLengths[0];
if (mn > 3) {
cout << 3 << endl;
} else {
cout << mn << endl;
}
}
}
void dfs (const vector<vector<ll>>& g, vector<bool> vis, ll v, ll& dfsDepth) {
stack<ll> s;
s.push(v);
while (!s.empty()) {
ll curr = s.top();
s.pop();
vis[curr] = 1;
dfsDepth++;
for (auto it : g[curr]) {
if (!vis[it]) {
s.push(it);
vis[it] = 1;
}
}
}
}