- sol1(시간초과): O(n2) 코드로 시간초과가 난다.
O(n) 풀이가 있다고 하는데, 내 뇌로는 O(n)은 생각나지 않아 풀이를 봤음
#include <bits/stdc++.h>
using namespace std;
int T, n;
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> T;
while(T--){
cin >> n;
set<int> ans;
vector<int> board(n+1, 0);
for(int i = 1; i <= n; ++i){
cin >> board[i];
}
for(int i = 1; i <= n; ++i){
stack<pair<int, int>> stk;
stk.push({i, 0});
while(!stk.empty()){
int cx = stk.top().first;
int cc = stk.top().second;
stk.pop();
int nx = board[cx];
if(i == nx){
ans.insert(i);
break;
}
if(nx < 1 || nx > n) continue;
if(cx == nx) break;
if(cc > 1) break;
stk.push({nx, cc+1});
}
}
cout << n - ans.size() << '\n';
}
return 0;
}
#include <iostream>
#include <queue>
#include <cstring>
#define MAX 100001
using namespace std;
int t, n;
int graph[MAX];
bool visited[MAX];
bool cycle[MAX];
int cnt;
void hasCycle(int node) {
visited[node] = true;
int next = graph[node];
if (!visited[next]) {
hasCycle(next);
}
else {
if (!cycle[next]) {
for (int i = next; i != node; i = graph[i]) cnt++;
cnt++;
}
}
cycle[node] = true;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> t;
while (t--) { cin >> n;
for (int i = 1; i <= n; i++) cin >> graph[i];
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
hasCycle(i);
}
}
cout << n-cnt << '\n';
cnt = 0;
fill(visited+1, visited+n+1, false);
fill(cycle+1, cycle+n+1, false);
}
return 0;
}