#include<cstdio>
#include<stack>
using namespace std;
stack <int> k;
bool d[1000005];
int f[1000005];
int ans[1000005];
int s[1000005];
int z;
struct IO_Tp
{
static const int _I_Buffer_Size = 1 << 24;
char _I_Buffer[_I_Buffer_Size];
char* _I_pos;
static const int _O_Buffer_Size = 1 << 24;
char _O_Buffer[_O_Buffer_Size];
char* _O_pos;
IO_Tp() : _I_pos(_I_Buffer), _O_pos(_O_Buffer)
{
fread(_I_Buffer, 1, _I_Buffer_Size, stdin);
}
~IO_Tp()
{
fwrite(_O_Buffer, 1, _O_pos - _O_Buffer, stdout);
}
inline bool is_digit(const char ch)
{
return '0' <= ch && ch <= '9';
}
inline IO_Tp& operator>>(int& res)
{
res = 0;
while (!is_digit(*_I_pos))
++_I_pos;
do
(res *= 10) += (*_I_pos++) & 15;
while (is_digit(*_I_pos));
return *this;
}
inline IO_Tp& operator<<(int n)
{
static char _buf[10];
char* _pos(_buf);
do
*_pos++ = '0' + n % 10;
while (n /= 10);
while (_pos != _buf)
*_O_pos++ = *--_pos;
return *this;
}
inline IO_Tp& operator<<(char ch)
{
*_O_pos++ = ch;
return *this;
}
} IO;
int mem(int n)
{
for(int i=1;i<=n;i++)
d[i]=0;
}
int tot=0;
void dfs(int x)
{
d[x]=1;
k.push(x);
int y=f[x];
if(ans[y]>0)
{
ans[x]=ans[y]+1;
return;
}
if(d[y]==1)
{
while(1)
{
s[++z]=k.top();
if(s[z]==y)
{
for(int i=1;i<=z;i++)
ans[s[i]]=z;
return;
}
k.pop();
}
return ;
}
d[y]=1;
dfs(y);
if(ans[x]==0)
ans[x]=ans[y]+1;
}
void nen()
{
for(int i=0;i<=z+1;i++)
s[i]=0;
z=0;
while(!k.empty())
k.pop();
}
int main()
{
int n;
IO>>n;
for(int i=1;i<=n;i++)
{
int a;
IO>>a;
f[i]=a;
}
for(int i=1;i<=n;i++)
{
if(ans[i]==0)
{
mem(n);
nen();
dfs(i);
}
}
for(int i=1;i<=n;i++)
IO<<ans[i]<<'\n';
}
算是记搜吧。