HDU 5656 CA Loves GCD--DP问题

CA Loves GCD

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 2300    Accepted Submission(s): 770


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.
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].
1T50
 

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
 题意,输入N个数,每一次随机拿出若干个数求他们的gcd并且加在一起,最后输出和是多少。

DP问题,我们设dp【i】【j】中的i表示前i个数字,j表示从前i个数字取出若干个数使他们的gcd是j。

之后会发现每一次求gcd会T,所以需要提前打表计算gcd。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long  a[1005],dp[1005][1005],GCD[1005][1005];
long long  gcd(long long a,long long b)
{
    return b?gcd(b,a%b):a;
}
int main()
{
    for(int i=1; i<=1000; i++)
        for(int j=1; j<=1000; j++)
            GCD[i][j]=gcd(i,j); ///提前打表,否则每一次调用gcd会超时
    int testnum;
    scanf("%d",&testnum);
    while(testnum--)
    {
        int num;
        scanf("%d",&num);
        memset(dp,0,sizeof(dp));
        for(int i=1; i<=num; i++)
            scanf("%d",&a[i]);
        for(int i=1; i<=num; i++)
        {
            dp[i][a[i]]=1; ///表示前i-1个都不取,仅仅取第i个
            for(int j=1; j<=1000; j++)   ///j遍历
            {
                dp[i][j]=(dp[i][j]+dp[i-1][j])%100000007; ///这个数字不取
                if(dp[i-1][j])  ///取这个数字,并求这个数和这个数之前的最大公约数的gcd
                    dp[i][GCD[a[i]][j]]=(dp[i][GCD[a[i]][j]]+dp[i-1][j])%100000007;
                    ///该处不能写成dp[i][GCD[a[i]][j]]=dp[i-1][j]%100000007
                    ///因为本身也要加上,而且GCD[a[i]][j]]一定是比j小的,所以不会漏掉数据
            }
        }
        long long sum=0;
        for(int j=1; j<=1000; j++) ///只需遍历最后,因为之前的方案数都推到后面了
            if(dp[num][j])
                sum=(sum+dp[num][j]*j)%100000007;
        printf("%lld\n",sum);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值