CodeForces 742C Arpa's loud Owf and Mehrdad's evil plan

题意:对于给定的一个数列 nxt[n] ,如果现在点 i ,那么下一个点就在nxt[i],现在问给定 n 个,找到一个最小的t,使得对于从任意一个点 x 出发,经过t次之后,到达的点 y , 使得点y经过 t 次之后会回到点x.

思路:

  • 首先,这是一个 n 个点n条边的有向图。

  • 现在要求对于从对任意点 x 出发经过2t次之后能够回到原点

  • 那么这个比较明显的要求这个图是必定是一个环或者多个环。

  • 考虑环上的点数如果是奇数 Go ,那么必定要经过 t=k×Go 次回到原点才能使得条件成立

  • 考虑环上的点数如果是偶数 Ge ,那么从这个点出发只要经过 t=(Ge)/2 次达到一个新的点,然后从这个新的点出发再经过 t=(Ge)/2 次就能回到起点。

  • 如果图上的点不是环,那么输出 1 ,

  • 反之,输出 ans=lcm(G0,G1,G2,,Gm)

  • 所以这个问题就变成了找环的问题

#include <cstdio>
#include <string>
#include<iostream>
#include<vector>
#include <stack>
#include <queue>
#include <map>
#include <cstdlib>
#include<string.h>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <set>

using namespace std;

typedef long long ll;
typedef pair<int, int>pii;
typedef pair<ll, ll> pll;
typedef pair<int, ll> pil;
typedef vector<vector<ll> >vvi;
typedef vector<ll> vi;

const ll mod = 1e9 + 7;
const int MAXN = 1000;
const int MAXM = 1000;
ll gcd(ll x, ll y)
{
    return y == 0 ? x : gcd(y, x%y);
}

ll lcm(ll x, ll y)
{
    return x / gcd(x, y)*y;
}

int nxt[140];
int fa[140];
int vis[140];
int nowc = 0;
int flag = 1;

int main()
{
    int n;
    cin >> n;

    ll ans = 0;
    for (int i = 1; i <= n; i++)scanf("%d", &nxt[i]);
    for (int i = 1; i <= n; i++)
    {
        if (!fa[i])
        {
            int now = i;
            int cot = 0;
            while (fa[nxt[now]] == 0)
            {
                fa[nxt[now]] = now;
                cot++;
                now = nxt[now];
            }
            if (now != i||fa[now]==0)
                flag = 0;
            else
            {
                if ((cot & 1) == 0)
                {
                    if (ans == 0)ans = cot / 2;
                    else ans = lcm(ans, (ll)cot / 2);
                }
                else
                {
                    if (ans == 0)ans = cot;
                    else ans = lcm(ans, (ll)cot);
                }
            }
        }
    }
    if (flag)printf("%I64d\n", ans);
    else printf("-1\n");
    //system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值