【HDU5656】CA Loves GCD——动态规划

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

CA喜欢是一个热爱党和人民的优秀同♂志,所以他也非常喜欢GCD(请在输入法中输入GCD得到CA喜欢GCD的原因)。现在他有N个不同的数,每次他会从中选出若干个(至少一个数),求出所有数的GCD然后放回去。为了使自己不会无聊,CA会把每种不同的选法都选一遍,CA想知道他得到的所有GCD的和是多少。我们认为两种选法不同,当且仅当有一个数在其中一种选法中被选中了,而在另外一种选法中没有被选中。

分析: Dp[i][j]i,GCDjDp[i][GCD(a[i],j)]+=Dp[i1][j]

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

using namespace std;

typedef long long LL;

const LL Mod = 100000007;

LL Dp[1100][1110];

int a[1100];

int gcd[1100][1100];

bool Hash[1100];

LL s[1100];

int GCD(int a,int b)
{
    return b==0?a:GCD(b,a%b);
}

void Init()
{
    for(int i = 1;i<=1000;i++)
    {
        for(int j =i;j<=1000;j++)
        {
            gcd[i][j] = gcd[j][i] = GCD(i,j);
        }
    }
}

int main() 
{
    int n;

    int T;

    Init();

    scanf("%d",&T);

    while(T--)
    {
        scanf("%d",&n);

        memset(Dp,0,sizeof(Dp));

        memset(Hash,false,sizeof(Hash));

        int num = 0;

        for(int i = 1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a+1,a+n+1);

        LL sum = 0;

        for(int i = 1;i<=n;i++)
        {
            for(int j = 0;j<num;j++)
            {
                Dp[i][s[j]] = Dp[i-1][s[j]];
            }

            int m =num;

            for(int j = 0;j<m;j++)
            {
                LL ans = gcd[s[j]][a[i]];

                Dp[i][ans]=(Dp[i][ans] + Dp[i-1][s[j]])%Mod;

                if(!Hash[ans])
                {
                    s[num++] = ans;

                    Hash[ans] = true;
                }
            }

            Dp[i][a[i]] = (Dp[i][a[i]]+1)%Mod;

            if(!Hash[a[i]])
            {
                s[num++] = a[i];

                Hash[a[i]] = true;
            }
        }

        for(int i = 0;i<num;i++)
        {
            sum = (sum+(s[i]*Dp[n][s[i]])%Mod)%Mod;
        }


        printf("%lld\n",sum%Mod);
    }
    return 0;
}

你可能感兴趣的:(【HDU5656】CA Loves GCD——动态规划)