CA Loves GCD
题目链接:
http://acm.hust.edu.cn/vjudge/contest/123316#problem/B
Description
CA is a fine comrade who loves the party and people; inevitably she loves GCD (greatest common divisor) too.
Now, there are 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 denoting the number of testcases.
testcases follow. Each testcase contains a integer in the first time, denoting , the number of the numbers CA have. The second line is numbers.
We guarantee that all numbers in the test are in the range [1,1000].
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
Hint
题意:
给出N(N<=1000)个不超过1000的数字;
对于每个子集可以求出该子集的最大公约数;
现在要求所有子集的最大公约数之和.
题解:
由于数字的规模不超过1000;
则可以直接用DP暴力枚举所有子集情况;
dp[i] 表示以i为最大公约的子集有多少个;
扫描这N个数字:
对于当前的num[i], 枚举其可能出现的最大公约数并计数:
int tmp = gcd(num[i], j);
dp[tmp] = (dp[tmp] + dp[j]) % mod;
很遗憾,直接枚举1-1000来更新dp会TLE;
优化途径:
1.将1000内任意两个数的gcd值打表.
2.每次枚举k时,若d[j]为0(即不存在以j为gcd的子集),则不需要更新(节省算gcd的时间);
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#define LL long long
#define eps 1e-8
#define maxn 1500
#define mod 100000007
#define inf 0x3f3f3f3f
#define IN freopen("in.txt","r",stdin);
using namespace std;
int n;
int num[maxn];
LL dp[maxn];
int gcc[1001][1001];
int main(int argc, char const *argv[])
{
//IN;
for(int i=1; i<=1000; i++) {
for(int j=1; j<=1000; j++) {
gcc[i][j] = __gcd(i,j);
}
}
int t; scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
for(int i=1; i<=n; i++)
scanf("%d", &num[i]);
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for(int i=1; i<=n; i++) {
for(int j=1; j<=1000; j++) {
int tmp = gcc[num[i]][j];
dp[tmp] = (dp[tmp] + dp[j]) % mod;
}
dp[num[i]]++;
}
LL ans = 0;
for(int i=1; i<=1000; i++) {
ans = (ans + i%mod*dp[i]) % mod;
}
printf("%I64d
", ans);
}
return 0;
}