Codeforces 524C Idempotent functions

题目链接:http://codeforces.com/problemset/problem/542/C

C. Idempotent functions
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Some time ago Leonid have known about idempotent functionsIdempotent function defined on a set {1, 2, ..., n} is such function , that for any  the formula g(g(x)) = g(x) holds.

Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x)f(k)(x) = f(f(k - 1)(x)) for each k > 1.

You are given some function . Your task is to find minimum positive integer k such that functionf(k)(x) is idempotent.

Input

In the first line of the input there is a single integer n (1 ≤ n ≤ 200) — the size of function f domain.

In the second line follow f(1), f(2), ..., f(n) (1 ≤ f(i) ≤ n for each 1 ≤ i ≤ n), the values of a function.

Output

Output minimum k such that function f(k)(x) is idempotent.

Sample test(s)
input
4
1 2 2 4
output
1
input
3
2 3 3
output
2
input
3
2 3 1
output
3

题目大意:给定一种运算f,对于输入的数组来说,一步操作,f(x) = a[x],两步操作,f^2(x) = a[a[x]]....倘若每次进行k步操作之后,得到的都是同一个数,即k为符合条件的步数。求出能令所有数都符合条件的最小步数。

初步我们可以很快想到,如果能求出每个数的符合条件的最小步数,然后求出这些步数的最小公倍数即可。但是需要注意的是,对于一开始并没有直接进入循环的情况,即"6"字形的情况,我们要分开求出多余的长度len[i]和循环节长度step[i],选出最长的MAXlen,ans即为MAXlen对所有step[i]的最小公倍数的上取整。


AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <cmath>
#include <algorithm>
using namespace std;
#define MAXN 500
typedef long long LL;
int n;
int a[MAXN];
LL step[MAXN];
int vis[MAXN], v[MAXN];
int main() {
    LL ans, maxNum = 0;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    for(int i = 1; i <= n; i++) {
        memset(vis, 0, sizeof(vis));
        stack<int> s;
        int j;
        for(j = i; !vis[j]; j = a[j]) {
            vis[j] = 1;
            s.push(j);
        }
        LL num = 1;
        while(s.top() != j) {
            s.pop(); num++;
        }
        s.pop();
        step[i] = num;
        maxNum = max(maxNum, (LL)s.size());
    }
    ans = step[1];
    for(int i = 1; i <= n; i++) {
        ans = ans / __gcd(ans, step[i]) * step[i];
    }
    LL temp = maxNum / ans;
    if(maxNum % ans || maxNum == 0) temp++;
    ans = temp * ans;
    printf("%I64d\n", ans);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值