您的位置:首页 > 其它

hdoj 5212 Code 【数学+思维】

2016-04-07 17:23 316 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: