Codeforces 524C Idempotent functions

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

题目大意:给定一种运算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;
}

 

  

 

posted @ 2015-05-07 12:07  gaoxiang36999  阅读(229)  评论(0编辑  收藏  举报