码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 5212(容斥原理)

时间:2015-04-27 02:05:15      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:容斥原理   组合数学   莫比乌斯反演   

Code

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


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
Hint
gcd(x,y) means the greatest common divisor of x and y.
 

Source
 

Recommend
hujie   |   We have carefully selected several similar problems for you:  5213 5209 5208 5205 5204 


给你一个a数组,让你计算那段代码的结果,用容斥原理就ok,莫比乌斯反演也行,不过不会莫比乌斯反演(也是容斥原理)orz。。。改天学习下。

代码如下:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 1e4 + 10;
const ll mod = 10007;
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define pb push_back
int cnt[maxn],a[maxn];
ll d[maxn];
int main()
{
        int n;
        while(~scanf("%d",&n)) {
            int Mgcd = 1;
            for(int i = 0; i < n; i++) {
                int x;
                scanf("%d",&x);
                Mgcd = max(Mgcd,x);
                a[i] = x;
            }
            memset(cnt,0,sizeof(cnt[0])*Mgcd+20);
            for(int i = 0; i < n; i++)cnt[a[i]]++;
            ll ans = 0,res = 0;
            /*d[i]表示任取两数gcd为i的方案数*/
            for(ll i = Mgcd; i > 0; i--) {
                ll tot = 0;
                for(ll j = i; j <= Mgcd; j+= i)
                {
                    tot += cnt[j];
                    d[i] = (d[i]-d[j])%mod;/*减去gcd为i的倍数的方案数(容斥原理)*/
                }
                /*gcd为i的方法数等于任选两个数(可重)是i的倍数的方案
                除去gcd为i的倍数的情况(前面已经减掉了)*/
                d[i] = (d[i] + tot*tot)%mod;
                ans = (d[i]*i*i)%mod;
                res = (res+i*d[i])%mod;
            }
            cout<<((ans-res)%mod+mod)%mod<<endl;
        }
        return 0;
}


hdu 5212(容斥原理)

标签:容斥原理   组合数学   莫比乌斯反演   

原文地址:http://blog.csdn.net/acvcla/article/details/45302039

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!