HDU 5212 Code(容斥 或 莫比烏斯反演),hdu5212
CodeTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Problem DescriptionWLD 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;
}
InputThere 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).
OutputFor each case:
Print an integer,denoting what the function returns.
Sample Input
51 3 4 2 4
Sample Output
64Hintgcd(x,y) means the greatest common divisor of x and y.
原文:http://www.cnblogs.com/JoeFan/p/4458629.html
題意:給出n個數,求gcd(a[i], a[j]) * gcd(a[i], a[j] - 1)的和(1 <= i, j <= n)。
分析:首先,我們分析每個數對最終答案的影響。那麼我們就要求出:對於每個數,以它為 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>#include <cmath>#include <algorithm>using namespace std;const int MaxN = 1e4 + 10;const int Mod = 10007;int cnt[MaxN], F[MaxN];int main() { int n, a; while(~scanf("%d", &n)) { 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 >= 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; int p = i * (i - 1) % Mod; ans = (ans + p * F[i] % Mod) % Mod; } printf("%d\n", ans); } return 0;}