hdu5656 dp

来源:互联网 发布:ip和端口查询 编辑:程序博客网 时间:2024/06/06 11:43

CA Loves GCD

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

思路:用dp[i][j]表示在前i个数中gcd为j的方案数,所以状态转移到dp[i+1][j]时,进行两步操作,设第i+1个数为v,dp[i+1][j] = dp[i][j];dp[i+1][gcd(v,j)]=dp[i][j];

#include <iostream>#include <algorithm>#include <cstring>using namespace std;int buf[1010][1010];int num[1010];int dp[1010][1010];int mod = 100000007;int gcd(int a, int b) {  //记忆化gcd,否则容易超时    if (buf[a][b])return buf[a][b];    if (b == 0)return buf[a][b] = a;    return buf[a][b] = buf[b][a % b] = gcd(b, a % b);}int main(){    int t;    scanf("%d",&t);    while (t--) {        int n;        scanf("%d",&n);        memset(dp, 0, sizeof(dp));        int Ma = 0;        for (int i = 1; i<=n; i++) {            scanf("%d",&num[i]);            Ma = max(Ma, num[i]);        }        for (int i = 1; i<=n; i++) {            dp[i][num[i]] = 1;            for (int j = 1; j<=Ma; j++) {                dp[i][j] += dp[i-1][j];                int t = gcd(num[i], j);                if(dp[i - 1][j])                dp[i][t] += dp[i-1][j];                dp[i][t] %= mod;            }        }        long long sum = 0;        for (int j = 1; j<=Ma; j++) {            sum += (long long)dp[n][j]*j;            sum %= mod;        }        printf("%lld\n",sum);    }}
0 0
原创粉丝点击