hdoj 5212 Code 【数学+思维】

题目链接:hdoj 5212 Code

Code

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

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(1≤N≤10000).

The next line contains N integers a1,a2,…,aN(1≤ai≤10000).

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.

题意:优化程序,快速求解。

思路:我们考虑以d为gcd的数对做出的贡献。
记a[]中d的倍数有cnt[d]个,在d的倍数中,会有若干个数组成数对的gcd为2*d,3*d……。我们设置ans[d]为以d为gcd的数对个数,那么有ans[d] = total - ans[2*d] - ans[3*d] - … 。其中total为cnt[d]*cnt[d]。
发现求解d,需要2*d、3*d……,而求解2*d需要3*d,4*d……。那么我们直接倒着来求就好了。时间复杂度O(nlogn)。

AC代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#include <cmath>
#define fi first
#define se second
#define ll o<<1
#define rr o<<1|1
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int MOD = 1e4 + 7;
const int MAXN = 1e4 + 10;
void add(LL &x, LL y) { x += y; x %= MOD; }
LL cnt[MAXN], ans[MAXN];
int main()
{
    int n;
    while(scanf("%d", &n) != EOF) {
        int Max = 0; CLR(cnt, 0);
        for(int i = 1; i <= n; i++) {
            int v; scanf("%d", &v);
            Max = max(Max, v);
            for(int j = 1; j <= sqrt(v); j++) {
                if(v % j == 0) {
                    cnt[j]++;
                    if(j * j != v) {
                        cnt[v/j]++;
                    }
                }
            }
        }
        CLR(ans, 0); LL sum = 0;
        for(int i = Max; i >= 1; i--) {
            ans[i] = cnt[i] * cnt[i];
            for(int j = i * 2; j <= Max; j += i) {
                ans[i] -= ans[j];
            }
            add(sum, ans[i] * (i-1) % MOD * i % MOD);
        }
        printf("%lld\n", sum);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值