*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;
}
posted @   Vijurria  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示