HihoCoder - 1330Array Rearrangement模拟+组合数学

题目链接:https://hihocoder.com/problemset/problem/1330

1330 : Array Rearrangement

Time Limit:10000ms
Case Time Limit:1000ms
Memory Limit:256MB

Description
Little Ho has written an array-shuffle program. It will shuffle an input array by some certain rearrangement order. Little Hi wants to know that after how many times of shuffle the array will come back to its original order?

More precisely, given a permutation P of 1 - N, the program shuffles the array by putting the i-th element into the Pi-th position. Assuming P = (2, 3, 1) and the initial array is (1, 2, 3), after the 1st shuffle it becomes (3, 1, 2), after the 2rd shuffle it becomes (2, 3, 1) and after the 3rd shuffle it comes back to (1, 2, 3).

You may assume the elements of input array are distinct.

Input
The first line contains an integer N, the length of the array. (1 ≤ N ≤ 100)
The second line contains the permutation P which consists of N integers.

Output
Output the number of shuffles.

Sample Input
3
2 3 1

Sample Output
3

题意:给定一个长度n,按照P数组的序列调整,求回到原始序列的最小步骤。

思路:对于每一个点分别通过模拟得出最小步骤,再求每个最小步骤的最小公倍数。开始的时候,直接就求了最大值,没有考虑到不同步的问题。还有因为是求最小公倍数,记得开long long 。
在这儿用%I64d会PE。

附上ac代码

#include<stdio.h>
typedef long long ll;
ll a[105];
ll GCD(ll a, ll b){
     if(a % b == 0)
          return b;
     return GCD(b, a % b);
}
ll LCM(ll a, ll b){
     return a * b / GCD(a, b);
}
int main(){
     int n;
     while(scanf("%lld", &n) != EOF){
          for(ll i = 1; i <= n; i++)
               scanf("%lld", &a[i]);
          ll ans = 1;
          //模拟
          for(ll i = 1; i <= n; i++){
               ll t = a[i];
               ll cnt = 1;
               while(t != i){
                    t = a[t];
                    cnt++;
               }
               ans = LCM(ans, cnt);
          }
          printf("%lld\n",ans);
     }
     return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值