CA Loves GCD
Time Limit: 6000/3000 MS (Java/Others)
Memory Limit: 262144/262144 K (Java/Others)
Problem Description
CA is a fine comrade who loves the party and people; inevitably she
loves GCD (greatest common divisor) too. Now, there are N different
numbers. Each time, CA will select several numbers (at least one), and
find the GCD of these numbers. In order to have fun, CA will try every
selection. After that, she wants to know the sum of all GCDs. If and
only if there is a number exists in a selection, but does not exist in
another one, we think these two selections are different from each
other.
Input
First line contains T denoting the number of testcases. T testcases
follow. Each testcase contains a integer in the first time, denoting
N, the number of the numbers CA have. The second line is N numbers.
We guarantee that all numbers in the test are in the range [1,1000].
1≤T≤50
Output
T lines, each line prints the sum of GCDs mod 100000007.
Sample Input
2
2
2 4
3
1 2 3
Sample Output
8
10
Source
BestCoder Round #78 (div.2)
题目大意:
n个数,所有可能组合gcd的和。
思路:
预处理gcd,dp求解。dp[i]表示gcd为i的组合数。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MOD = 100000007;
const int MAXN = 1010;
int dp[MAXN];
int gcd[MAXN][MAXN];
int a[MAXN];
int Gcd(int a, int b)
{
if(b && gcd[a][b])
return gcd[a][b];
if(b == 0)
return a;
return Gcd(b, a%b);
}
int main(int argc, char const *argv[])
{
memset(gcd, 0, sizeof(gcd));
for(int i = 1; i < MAXN; i++)
for(int j = 1; j < MAXN; j++)
gcd[i][j] = gcd[j][i] = Gcd(i, j);
int t;
scanf("%d", &t);
while(t--)
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
sort(a, a+n);
memset(dp, 0, sizeof(dp));
for(int i = 0; i < n; i++)
{
for(int j = 1; j <= a[i]; j++)
if(dp[j])
{
int k = gcd[a[i]][j];
dp[k] += dp[j];
dp[k] %= MOD;
}
dp[a[i]]++;
dp[a[i]] %= MOD;
}
long long ans = 0;
for(int i = 1; i <= a[n-1]; i++)
if(dp[i])
{
ans += (long long) i * dp[i];
ans %= MOD;
}
printf("%I64d\n", ans);
}
return 0;
}