#include<iostream>
#include<vector>
using namespace std;
int main(){
int n, m, k, j = 0;
cin>>n;
bool a[n];
int b[n];
for(int i = 0; i<n; i++) cin>>b[i];
for(int i = 0; i<n; i++) a[i] = false;
for(int i = 0; i<n; i++){
if(a[i]) continue;
a[i] = true;
k = b[i];
m = a[b[i]];
a[b[i]] = true;
while(!m){
a[b[k]] = true;
k = b[k];
m = a[b[k]];
}
j++;
}
cout<<j;
j = 0;
}
#include
#include
using namespace std;int main(){
int n, m, k, j = 0;
cin>>n;
bool a[n];
int b[n];
for(int i = 0; i>b[i];
for(int i = 0; i for(int i = 0; i
if(a[i]) continue;
a[i] = true;
k = b[i];
m = a[b[i]];
a[b[i]] = true;
while(!m){
a[b[k]] = true;
k = b[k];
m = a[b[k]];
}
j++;
}
cout< j = 0;
}
#include <iostream>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m,j=0;
cin>>n;
int a[n]={0},b[n];
for(int i=0;i<n;i++)cin>>b[i];
for(int i=0;i<n;i++){
if(!a[i]){
m=i;
while(!a[m]){
a[m]++;
m=b[m];
}
j++;
}
}
cout<<j;
return 0;
}
稍微參考修改一下...執行效率蠻高了