URAL1024 - Permutations

题意

已知,可得出 P(1) = 4, P(2) = 1, P(3) = 5,由此可得出 P(P(1)) = P(4) = 2. And P(P(3)) = P(5) = 3,因此。经过k次如上变换,最终可得,输入保证一定有解,求k。

(题意抄的人家的)

思路

模拟每一步,求出每个数字置换成a[i] = i时所需次数, 最后的结果为次数的最小公倍数

总结

WA了好几次 错在了lcm上,ans不会超int 但是lcm在乘的时候可能会超int,所以以后改成long long 或者先除后乘

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 using namespace std;
 6 const int maxn = 1e3 + 5;
 7 int a[maxn], num[maxn];
 8 int n;
 9 int gcd(int a, int b)
10 {
11 
12     return b == 0 ? a : gcd(b, a%b);
13 }
14 int lcm(int a, int b)
15 {
16     return a / gcd(a, b) * b;
17 }
18 int main()
19 {
20     //freopen("in.txt", "r", stdin);
21     cin >> n;
22     for(int i = 1; i <= n; i++){
23         cin >> a[i];
24     }
25     for(int i = 1; i <= n; i++) {
26         num[i] = 1;
27         int t = a[i];
28         while(t != i) {
29             t = a[t];
30             num[i] ++;
31         }
32     }
33 
34     int ans = num[1];
35     for(int i = 2; i <= n; i++) {
36         ans = lcm(ans, num[i]);
37     }
38     cout << ans << endl;
39     return 0;
40 }

 

转载于:https://www.cnblogs.com/kikii233/p/6053692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值