1. 程式人生 > 實用技巧 >牛客網Bogo Sort

牛客網Bogo Sort

題目描述:

Today Tonnnny the monkey learned a new algorithm called Bogo Sort. The teacher gave Tonnnny the code of Bogo sort:

The teacher said the shuffle function is to uniformly randomly permute the array with length , and the algorithm's expectation complexity is O(n⋅n!)O(n \cdot n!)O(nn!).
However, Tonnnny is a determined boy — he doesn't like randomness at all! So Tonnnny improved Bogo Sort. He had chosen one favourite permutationwith length , and he replaced the random shuffle with shuffle of , so the improved algorithm, Tonnnny Sort, can solve sorting problems for length array — at least Tonnnny thinks so.

Tonnnny was satsified with the new algorithm, and decided to let you give him a different array of length every day to sort it with Tonnnny Sort.

You are the best friend of Tonnnny. Even though you had found the algorithm is somehow wrong, you want to make Tonnnny happy as long as possible. You're given N,pN,\ pN,p, and you need to calculate the maximum number of days that Tonnnny will be happy, since after that you can't give Tonnnny an array that can be sorted with Tonnnny Sort and didn't appeared before.

The answer may be very large. Tonnnny only like numbers with at mostdigits, so please output answer mod10N10^N10N instead.

輸入1:

5
1 2 3 4 5

輸出1:
1
輸入2:
6
2 3 4 5 6 1
輸出2:
6



  • 首先這題需要高精度。就尼瑪噁心。
  • 之後腦袋一拍我們就知道這題需要找到環的長度的;
  • 並且求出這些環長度的最小公倍數;
  • 然後就沒有然後了。

上程式碼:

#include<bits/stdc++.h>
using namespace std;
int n,m;
int len=1;
int sum,tot;
int z[100100];
int za[100100];
int s[1000010];
int v[1000010];
int a[1000010];
int ans[1000010];
void add(int x)
{
    for (int i=1; i<=len; i++) ans[i]*=x;
    for (int i=1; i<len; i++) ans[i+1]+=ans[i]/10,ans[i]%=10;
    while (len<n && ans[len]>=10) ans[len+1]+=ans[len]/10,ans[len]%=10,len++;
    ans[len+1]=0;
}
int main()
{
    for (int i=2; i<1e5+10; i++)
    {
        int f=0,num=0;
        for (int j=1; j*j<=i; j++)
        {
            if (i%j==0) num++;
            if (num>1)
            {
                f=1;
                break;
            }
        }
        if (f==1) continue;
        sum++;
        z[sum]=i;
    }
    ans[1]=1;
    v[1]=1;
    cin>>n;
    for (int i=1; i<=n; i++) scanf("%d",&a[i]);
    for (int i=1; i<=n; i++)
        if (v[i]==0)
        {
            v[i]=1;
            s[++tot]=1;
            for (int j=a[i]; j!=i; j=a[j])
                v[j]=1,s[tot]++;
        }
    for (int i=1; i<=tot; i++)
    {
        for (int j=1; j<=sum; j++)
        {
            int num=0;
            while (s[i]%z[j]==0) num++,s[i]/=z[j];
            za[j]=max(num,za[j]);
            m=max(j,m);
        }
    }
    for (int i=1; i<=m; i++)
    for (int j=1; j<=za[i]; j++)
        add(z[i]);
    for (int i=len; i>=1; i--) cout<<ans[i]%10;
}//有點醜別建議;
View Code