Hdoj 5212 Code 【数论】【莫比乌斯 反演】

本文介绍了一种针对特定函数的高效计算方法,通过分析数列中每对数的贡献来优化计算过程,实现了O(nlogn)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://blog.youkuaiyun.com/LYHVOYAGE/article/details/45306211

Code

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 212    Accepted Submission(s): 86


Problem Description
WLD likes playing with codes.One day he is writing a function.Howerver,his computer breaks down because the function is too powerful.He is very sad.Can you help him?

The function:


int calc
{
  
  int res=0;
  
  for(int i=1;i<=n;i++)
    
    for(int j=1;j<=n;j++)
    
    {
      
      res+=gcd(a[i],a[j])*(gcd(a[i],a[j])-1);
      
      res%=10007;
    
    }
  
  return res;

}
 

Input
There are Multiple Cases.(At MOST  10 )

For each case:

The first line contains an integer  N(1N10000) .

The next line contains  N  integers  a1,a2,...,aN(1ai10000) .
 

Output
For each case:

Print an integer,denoting what the function returns.
 

Sample Input
  
5 1 3 4 2 4
 

Sample Output
  
64

分析:首先,我们分析每个数对最终答案的影响。
那么我们就要求出:对于每个数,以它为 gcd 的数对有多少对。
显然,对于一个数 x ,以它为 gcd 的两个数一定都是 x 的倍数。如果 x 的倍数在数列中有 k 个,那么最多有 k^2 对数的 gcd 是 x 。

同样显然的是,对于两个数,如果他们都是 x 的倍数,那么他们的 gcd 一定也是 x 的倍数。

所以,我们求出 x 的倍数在数列中有 k 个,然后就有 k^2 对数满足两个数都是 x 的倍数,这 k^2 对数的 gcd,要么是 x ,要么是 2x, 3x, 4x...

并且,一个数是 x 的倍数的倍数,它就一定是 x 的倍数。所以以 x 的倍数为 gcd 的数对,一定都包含在这 k^2 对数中。

如果我们从大到小枚举 x ,这样计算 x 的贡献时,x 的多倍数就已经计算完了。我们用 f(x) 表示以 x 为 gcd 的数对个数。

那么 f(x) = k^2 - f(2x) - f(3x) - f(4x) ... f(tx)       (tx <= 10000, k = Cnt[x])

这样枚举每个 x ,然后枚举每个 x 的倍数,复杂度用调和级数计算,约为 O(n logn)。 

代码:

 #include <cstdio>
 #include <cstring>
 const int M = 1e4+5;
 const int Mod = 10007;
 using namespace std;
 
 int cnt[M], f[M];
 
 int main(){
 	int n, a;
 	while(scanf("%d", &n) == 1){
	 	memset(cnt, 0, sizeof(cnt));
	 	for(int i = 0; i < n; ++ i){
		 	scanf("%d", &a);
		 	for(int j = 1; j*j <= a; ++ j){
			 	if(a%j == 0){
				 	cnt[j]++;
				 	if(j*j != a){
					 	cnt[a/j]++;
					 }
				 }
			 }
		 }
		 int ans = 0;
		 for(int i = 10000; i > 0; -- i){
		 	f[i] = cnt[i]*cnt[i]%Mod;
		 	for(int j = i*2; j <= 10000; j += i){
			 	f[i] = (f[i]-f[j]+Mod)%Mod;
			 }
			 int temp = i*(i-1)%Mod;
			 ans = (ans+(temp*f[i])%Mod)%Mod;
		 }
		 printf("%d\n", ans);
	 }
 	return 0;
 } 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值