Idea 1:
Violence
Code:
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;
const int N = 10010;
int a[N];
int cnt,n;
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
{
scanf("%d",&a[i]);
}
for(int i = 1;i <= n;i++)
{
while(i != a[i])
{
swap(a[i],a[a[i]]);
cnt++;
}
}
printf("%d\n",cnt);
return 0;
}
Idea 2:
Use the operating code of the ring
:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1e5+5;
int a[N];
bool st[N];
int main(){
int n;
cin >> n;
for(int i=1;i<=n;i++){
cin >> a[i];
}
int cnt=0;
for(int i=1;i<=n;i++){
if(!st[i]){
cnt++;
for(int j=i;!st[j];j=a[j]){
//位置j指向a[j]的元素
st[j]=true;
}
}
}
cout << n-cnt;
}