Color POJ - 2154 (Polya定理)(欧拉函数优化)

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
这道题就是各种数学定理的应用
首先是可以确定是使用Polya定理
因为只考虑旋转的重复的问题,所以可以确定,对于一个数量为n的串,那么其置换群的大小为n(不包括对换的情况)
那么对于每个群所得的循环节的大小,我们可以通过gcd(i,n)来计算,但是可以发现,n的范围太大,逐个枚举铁定会超时,这里用得到技巧是不去枚举i,而去枚举每个循环节的长度设为L。
设d=gcd(i,n)
那么n=L*d,
对于i,我们设a使得i=a*d,
那么可知a和L必然互质,假设我们先确定了L,那么我们就只需要去找有多少个不同的d与L互质,这就是应用到了欧拉函数,那么在L下,一共有euler(L)个d,也就是有多少个i。
到此我们就可以去枚举L了,然后计算与之相应的euler(L)值。
但是即使如此,线性枚举L还是有超时的可能

当n%L==0满足时,其实际上n/L也是满足能被n整除,而我们就可与利用这个额外的信息去优化也就是折半枚举
这道题的到这里的处理和HDU-2588如出一辙
代码:

import java.util.Scanner;



public class Main 
{
    static int mod;
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while((t--)>0)
        {
            int n=sc.nextInt();
            mod=sc.nextInt();
            long ans=0;
            int i=0;
            for(i=1;i*i<n;i++)
            {
                if(n%i==0)//然后能整除,那我们就得到了i和n/i两个可除的数
                    ans=(ans+quick(n,n/i-1)*euler(i)+quick(n,i-1)*euler(n/i))%mod;
            }
            if(i*i==n)//如果恰n可开放,那么在这种情况下只要除一次
                ans=(ans+quick(n,i-1)*euler(i))%mod;
            System.out.println(ans);
        }
    }
    static long quick(int a,int b)//这里为了处理Polya部分的幂运算,使用了快速mi加速
    {
        long ans=1;
        a%=mod;
        while(b>0)
        {
            if((b&1)==1)
            {
                ans=(ans*a)%mod;
            }
            a=a*a%mod;
            b>>=1;
        }
        return ans;
    }
    static int euler(int n)//欧拉函数
    {
        int res=n;
        for(int i=2;i*i<=n;i++)
        {
            if(n%i==0)
            {
                res-=res/i;
                while(n%i==0)
                    n/=i;
            }
        }
        if(n>1)
            res-=res/n;
        return res%mod;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值