#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;
}
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;
if (a == b)
{
cout << "0\n";
continue;
}
bool usecyclerev = 0;
if (partofcycle[a] && partofcycle[b])
{
if (dep[a] < dep[b])
{
swap(a, b);
usecyclerev = 1;
}
}
int u = a;
int v = b;
if (dep[a] < dep[b])
{
cout << "-1\n";
continue;
}
for (int i = 0; i < 20; i++)
{
if ((dep[a] - dep[b]) & (1 << i))
a = jump[i][a];
}
if (a == b)
{
if (usecyclerev)
cout << (lenofcycle[u] - dep[u] + dep[v]) << "\n";
else
cout << dep[u] - dep[v] << "\n";
}
else
cout << "-1\n";
}
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKI2RlZmluZSBzeiAyMDAxMDAKI2RlZmluZSBNT0QgMTAwMDAwMDAwNwojZGVmaW5lIGxsIGxvbmcgbG9uZwppbnQgY2hbc3pdOwpib29sIHZpc1tzel07CmludCBkZXBbc3pdOwppbnQganVtcFsyMF1bc3pdOwpib29sIHBhcnRvZmN5Y2xlW3N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