题意
已知,可得出 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 }