Codeforces 524C Idempotent functions
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Codeforces 524C Idempotent functions
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                題目鏈接:http://codeforces.com/problemset/problem/542/C
題目大意:給定一種運算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; }?
?
轉載于:https://www.cnblogs.com/gaoxiang36999/p/4484456.html
總結
以上是生活随笔為你收集整理的Codeforces 524C Idempotent functions的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: BIEE入门(一)架构
- 下一篇: 华为:明明的随机数
