HDU 5656 CA Loves GCD

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5656


题意:有N个不同的数,每次从中选出若干个(至少一个数),求出所有数的GCD然后放回去。求所有选择的GCD之和是多少。


思路:由于每个数的范围很小,所以用dp[i][j]来表示前i个数中选取若干个使得gcd为j的方案总数。

1、不选取ai,dp[i][j]+=dp[i-1][j]

2、选取ai,dp[i][ai]++  dp[i][gcd(ai,j)]+=dp[i-1][j]

再用一个数组记录一下gcd,不然可能会超时。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007
const int maxn = 1002;

LL dp[maxn][maxn];
int n,T;
int a[maxn];

int g[maxn][maxn];

int gcd(int a,int b)
{
    if ( g[a][b] != -1 ) return g[a][b];

    return g[a][b] = g[b][a] = (b==0)?a:gcd(b,a%b);
}


int getnum()
{
    int ans = 0;
    char c = getchar();
    while( !isdigit(c) ) c = getchar();

    while( isdigit(c) )
    {
        ans = ans * 10 + c - '0';
        c = getchar();
    }
    return ans;
}
int main()
{
    Clean(g,-1);
    T = getnum();
    while(T--)
    {
        Clean(dp,0);
        n = getnum();
        int uplim = 0;
        rep(i,1,n)
        {
            a[i] = getnum();
            uplim = max(uplim,a[i]);
        }
        dp[1][a[1]] = 1;
        rep(i,2,n)
        {
            dp[i][a[i]]++;
            rep(j,1,uplim)
            {
                dp[i][gcd(a[i],j)]+=dp[i-1][j];
                dp[i][gcd(a[i],j)]%=100000007;
                dp[i][j]+=dp[i-1][j];//不选a[i]
                dp[i][j]%=100000007;
            }
        }
        LL ans = 0;
        rep(i,1,uplim) ans=(ans+i*dp[n][i])%100000007;
        printf("%I64d\n",ans%100000007);
    }

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值