序列置换
时间限制:3000 ms | 内存限制:65535 KB
难度:3
描述
有一个数字序列A{a1,a2,a3,a4 .... an}和一个调整策略T{t1,t2,t3,t4 .... tn},
其中调整策略的序列表示:
a1将转换到A序列的t1位置,
a2将转换到A序列的t2位置
....
求按照T策略转换多少次能还原A序列(最少一次)。
输入
每组测试数据两行(最多1000组)
第一行一个整数 n (1 <= n <= 200)
第二行 n 个整数 ti (1 <= ti <= n) 任意 ti 不重复
输出
一行一个整数表示答案
样例输入
4
1 2 3 4
3
2 3 1
样例输出
1
3
这一题不能直接求,要分开逐个模拟,然后求最小公倍数,实现很简单
AC代码
# include <stdio.h>
# include <string.h>
long long ans;
int change[210];
long long int cnt[210];
long long int gcd(long long int a, long long int b){
if(a%b==0){
return b;
}
return gcd(b, a%b);
}
int main(){
int n, i, j, k, cur;
while(scanf("%d", &n)!=EOF){
for(i=1; i<=n; i++)
scanf("%d", &change[i]);
memset(cnt, 0, sizeof(cnt));
for(i=1; i<=n; i++){
cur=i;
do{
cur=change[cur];
cnt[i]++;
}while(cur!=i);
}
ans=cnt[1];
for(i=2; i<=n; i++){
ans=ans*cnt[i]/gcd(ans, cnt[i]);
}
printf("%lld\n", ans);
}
return 0;
}