#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
#define FOR(i,a,b) for(i=(a);i<=(b);i++)
#define ROF(i,a,b) for(i=(a);i>=(b);i--)
#define mmt(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define mp make_pair
#define inf 1e9
#define N 1000100
using namespace std;
typedef long long LL;
typedef long double LD;
int last[N],pre[N],e[N],f[N][2],Nxt[N],vis[N],len=0,cir[N],tu,n,col=0;
void add(int x,int y){pre[++len]=last[x];last[x]=len;e[len]=y;}
void DFS(int x)
{
if (vis[x])
{
if (vis[x]!=col) return;
if (cir[x]) return;
cir[x]=1;
for(int p=Nxt[x];p!=x;p=Nxt[p]) cir[p]=1;
return;
}
vis[x]=col;
DFS(Nxt[x]);
}
void DP(int u,int root)
{
vis[u]=1;
bool end=1,xz=0;;
for(int p=last[u];p;p=pre[p])
{
int v=e[p];
if (v==root) tu=u;
else
{
DP(v,root);end=0;
int tt=max(f[v][1],f[v][0]);
if (tt==f[v][0]) xz=1;
f[u][1]+=tt;f[u][0]+=tt;
}
}
if (!xz)
{
int delta=1e9;
for(int p=last[u];p;p=pre[p])
{
int v=e[p];
if (v==root) continue;
delta=min(delta,f[v][1]-f[v][0]);
}
f[u][1]-=delta;
}
if (end) f[u][0]=f[u][1]=0;
else f[u][1]++;
}
void collect_DP(int x,int ban,int bf0,int bf1,int &tf0,int &tf1,bool bk=1)
{
tf1=1,tf0=0;int ff0,ff1;bool xz=0;
for(int p=last[x];p;p=pre[p])
{
int v=e[p];
if (v==ban) ff0=bf0,ff1=bf1;else ff0=f[v][0],ff1=f[v][1];
if (v==ban&&!bk) continue;
int tt=max(ff0,ff1);
if (tt==ff0) xz=1;
tf0+=tt,tf1+=tt;
}
if (!xz)
{
int delta=1e9;
for(int p=last[x];p;p=pre[p])
{
int v=e[p];
if (v==ban) ff0=bf0,ff1=bf1;else ff0=f[v][0],ff1=f[v][1];
if (v==ban&&!bk) continue;
delta=min(delta,ff1-ff0);
}
tf1-=delta;
}
}
int main()
{
ios::sync_with_stdio(false);
int i,ans=0;
scanf("%d",&n);
FOR(i,1,n)
{
scanf("%d",&Nxt[i]);
add(Nxt[i],i);
}
mmt(vis,0);
FOR(i,1,n)
{
if (!vis[i]) {col++;DFS(i);}
}
mmt(vis,0);
FOR(i,1,n)
if (!vis[i]&&cir[i])
{
DP(i,i);
int f0,f1,lst;
collect_DP(tu,i,0,0,f0,f1);f1=-1e9;lst=tu;
for(int p=Nxt[tu];p!=tu;lst=p,p=Nxt[p])
{
int v=p,tf0,tf1;
collect_DP(v,lst,f0,f1,tf0,tf1);
f0=tf0;f1=tf1;
}
int r1=max(f0,f1);
collect_DP(tu,i,-1e9,-1e9,f0,f1,0);f0=-1e9;lst=tu;
for(int p=Nxt[tu];p!=tu;lst=p,p=Nxt[p])
{
int v=p,tf0,tf1;
collect_DP(v,lst,f0,f1,tf0,tf1);
f0=tf0;f1=tf1;
}
int r2=max(f0,f1);
collect_DP(tu,i,0,0,f0,f1);f0=-1e9;lst=tu;
for(int p=Nxt[tu];p!=tu;lst=p,p=Nxt[p])
{
int v=p,tf0,tf1;
collect_DP(v,lst,f0,f1,tf0,tf1);
f0=tf0;f1=tf1;
}
int r3=f0;
if (tu==i) ans+=max(f[tu][0],f[tu][1]);
else ans+=max(max(r1,r2),r3);
}
printf("%d\n",ans);
return 0;
}