题目链接:http://codeforces.com/problemset/problem/542/C
Some time ago Leonid have known about idempotent functions. Idempotent 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.
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 minimum k such that function f(k)(x) is idempotent.
4 1 2 2 4
1
3 2 3 3
2
3 2 3 1
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;
}