*Acwing(第72场周赛) 4626. 最小移动距离(并查集)
https://www.acwing.com/problem/content/4629/
//基环树
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18;
const LL N=200200,M=2002;
LL n,father[N],d[N],s[N];
LL find(LL x)
{
if(father[x]!=x) father[x]=find(father[x]);
return father[x];
}
LL cal()
{
for(LL i=1;i<=n;i++)
{
if(d[i]!=1) return -1;//如果入度数量不为1,直接返回-1
}
LL res=1;
for(LL i=1;i<=n;i++)
{
if(father[i]==i)
{
LL len=s[i];
if(len%2==0) len/=2;
res=res*(len/__gcd(res,len));//lcm最小公倍数
}
}
return res;
}
int main()
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
LL T=1;
//cin>>T;
while(T--)
{
cin>>n;
for(LL i=1;i<=n;i++)
{
father[i]=i;
s[i]=1;//初始化每个点都有一个入度,形成自环
}
for(LL i=1;i<=n;i++)
{
LL x;
cin>>x;
d[x]++;
LL fi=find(i),fx=find(x);
if(fi!=fx)
{
s[fx]+=s[fi];//数量合并
father[fi]=fx;
}
}
cout<<cal()<<endl;
}
return 0;
}