#include<bits/stdc++.h>
using namespace std;
#define sz 200100
#define MOD 1000000007
#define ll long long
int ch[sz];
bool vis[sz];
int dep[sz];
int jump[20][sz];
bool partofcycle[sz];
int lenofcycle[sz];
void dfs(int s)
{
vis[s] = 1;
if (!vis[ch[s]])
dfs(ch[s]);
else if (!dep[ch[s]])
{
int v = s;
int len = 0;
do
{
partofcycle[v] = 1;
v = ch[v];
len++;
}
while (v != s);
do
{
lenofcycle[v] = len;
v = ch[v];
}
while (v != s);
}
dep[s] = dep[ch[s]] + 1;
}
bool anc(int a, int b, int diff)
{
for (int i = 0; i < 20; i++)
{
if (diff & (1 << i))
a = jump[i][a];
}
return (a == b);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> ch[i];
jump[0][i] = ch[i];
}
for (int i = 1; i <= n; i++)
{
if (!vis[i])
dfs(i);
}
for (int i = 1; i < 20; i++)
{
for (int j = 1; j <= n; j++)
jump[i][j] = jump[i - 1][jump[i - 1][j]];
}
while (m--)
{
int a, b;
cin >> a >> b;
int u = a; int v = b;
if (a == b)
{
cout << "0\n";
continue;
}
int diff = dep[a] - dep[b];
if (diff > 0 && anc(a, b, diff))
{
cout << diff << "\n";
continue;
}
if (partofcycle[b])
{
diff = dep[a] - dep[b] + lenofcycle[b];
if (diff > 0 && anc(a, b, diff))
{
cout << diff << "\n";
continue;
}
}
cout << "-1\n";
}
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKI2RlZmluZSBzeiAyMDAxMDAKI2RlZmluZSBNT0QgMTAwMDAwMDAwNwojZGVmaW5lIGxsIGxvbmcgbG9uZwppbnQgY2hbc3pdOwpib29sIHZpc1tzel07CmludCBkZXBbc3pdOwppbnQganVtcFsyMF1bc3pdOwpib29sIHBhcnRvZmN5Y2xlW3N6XTsKaW50IGxlbm9mY3ljbGVbc3pdOwp2b2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