AC_osiris

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

说实话,我觉得莫比乌斯反演真是个神奇的定理,可以简化计算(学习莫比乌斯反演请看ppt),这题是莫比乌斯性质或者说是容斥原理的一个基本的应用。

http://acm.hdu.edu.cn/showproblem.php?pid=5212

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

 

题意:给出n个数,求gcd(a[i], a[j]) * gcd(a[i], a[j] - 1)的和(1 <= i, j <= n)。

之前看那个ppt的时候也有类似的问题就是求gcd(x,y)=k的对数,这里也是要求gcd(a[i],a[j]),显然的是我们不能直接枚举所有的情况,首先我们考虑每个数对结果的影响,

那么我们就要求出:对于每个数,以它为 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])(这里用到的就是容斥原理,当然,它也是莫比乌斯反演的变形,一般设计到约数和或者倍数和的,都会用到这个,说实话我现在也不是很会这个,等我慢慢研究下?)

最后的时间复杂度大概是O(n*logn);

#include <cstdio>
#include <cstring>
#include<iostream>
#include <algorithm>
using namespace std;
#define  Mod 10007
int cnt[10010], f[10010];
int n;
int main() {
    while(scanf("%d",&n)!=EOF) {

       int a;
        memset(cnt, 0, sizeof(cnt));
        for(int i = 0; i < n; i++) {//找到序列中所有数的所有约数,并用cnt[]记录个数
            scanf("%d", &a);
            for(int j = 1; j * j <= a; j++) {
                if(a % j == 0) {
                    cnt[j]++;//找到a的约数,cnt[j]为约数为j的个数
                    if(j * j != a)
                       cnt[a / j]++;
                }
            }
        }
        long long  ans = 0;
        for(int i = 10000; i >= 1; 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;

        //计算出f[i]
            int p=i * (i - 1) % Mod;
            ans +=p * f[i] % Mod;//约数为i的按照题意乘起来相加,f[i]表示数对的个数
            ans=ans%Mod;
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

posted on 2015-05-08 16:24  AC_osiris  阅读(215)  评论(0)    收藏  举报