#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second

int state[100005]={0};
int num[100005]={0};

const int IN=-1;
const int not_vis=0;

void run(int x) {
    int cur=x;
    while(1) {
        //시작 숫자로 표시
        state[cur]=x;
        //다음 숫자로 넘어감
        cur=num[cur];
        //싸이클임
        if(state[cur]==x) {
            while(state[cur] != IN) {
                state[cur]=IN;
                cur=num[cur];
            }
            return;
            //이전에 방문함
        } else if(state[cur]!= not_vis) return;
    }
}

int main() {
    cin.tie(0);
    int t;
    cin >> t;
    while(t--) {
        int n;
        cin >> n;
        fill(state+1,state+n+1,0);
        for(int i=1; i<=n; i++) {
            cin >> num[i];
        }
        for(int i=0; i<=n; i++) {
            if(state[i]==not_vis) run(i);
        }
        int cnt=0;
        for(int i=1; i<=n; i++) {
            if(state[i]!=In) cnt++;
        }
        cout << cnt <<'\n';
    }
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: