POJ2154——Color(Polya定理+篩素數+歐拉函數)

Color
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 6292 Accepted: 2090
Description

Beads of N colors are connected together into a circular necklace of N beads (N<=1000000000). Your job is to calculate how many different kinds of the necklace can be produced. You should know that the necklace might not use up all the N colors, and the repetitions that are produced by rotation around the center of the circular necklace are all neglected. 

You only need to output the answer module a given number P. 
Input
The first line of the input is an integer X (X <= 3500) representing the number of test cases. The following X lines each contains two numbers N and P (1 <= N <= 1000000000, 1 <= P <= 30000), representing a test case.
Output
For each test case, output one line containing the answer.
Sample Input
5
1 30000
2 30000
3 30000
4 30000
5 30000
Sample Output
1
3
11
70
629
Source

POJ Monthly,Lou Tiancheng

解析:

        Poj2154的N比較大,10^9的範圍,但是隻有旋轉這種置換,沒有翻轉。
        如果我們按照O(n)的做法,即∑m^gcd(n,i),顯然是要超時的,所以需要換一種思路來計算。 
        設循環節長度爲a=gcd(n,i),則一個循環的長度爲L=n/a。由以上兩式可以得到gcd(L*a,k*a)=a,其中k爲不超過L的整數。進一步化簡得到gcd(L,k)=1,那麼滿足這個式子的         循環的個數,也就是k的個數,就是euler(L),euler代表歐拉函數(小於L且與L互質的數的個數)。
        所以答案就是(∑euler(L)*m^(n/L)) / n,本題中m=n,上式也就是(∑euler(L)*n^(n/L-1)。因此只需要枚舉n的約數L,L從1枚舉到sqrt(n)即可,因爲另一個約數就是n/L。注意         當L*L=n的時候別重複算。時間複雜度O(n^0.5logn)。

代碼:

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

int n,mod,test,m=0;
bool col[50000];
int a[32000];

void prime(int n)
{
    for(int i=2;i<=n;i++)
    {
        if(!col[i])
        {
            a[++m]=i;
            for(int j=i*i;j<=n;j+=i)col[j]=true;
        }
    }
}

int quick(int a,int b)
{
    int tmp=1;
    for(a%=mod;b;b>>=1)
    {
        if(b&1)tmp=tmp*a%mod;
        a=a*a%mod;
    }
    return tmp;
}

int euler(int n)
{
    int tmp=n;
    for(int i=1;i<=m,a[i]*a[i]<=n;i++)
        if(n%a[i]==0)
        {
            tmp=tmp/a[i]*(a[i]-1);
            while(n%a[i]==0)n/=a[i];
        }
    if(n>1)tmp=tmp/n*(n-1);
    return tmp%mod;
}
int main()
{
    freopen("poj2154.in","r",stdin);
    freopen("poj2154.out","w",stdout);
    scanf("%d",&test);
    prime(32000);
    while(test--)
    {
        int ans=0,i;
        scanf("%d%d",&n,&mod);
        for(i=1;i*i<n;i++)
            if(n%i==0)ans=(ans+euler(i)*quick(n,n/i-1)+euler(n/i)*quick(n,i-1))%mod;
        if(i*i==n)ans=(ans+euler(i)*quick(n,i-1))%mod;
        printf("%d\n",ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章