HDU 5656 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].
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
相当于做背包的dp,gcd的处理用记忆化的。
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<bitset>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
typedef long long LL;
const int low(int x){ return x&-x; }
const int INF = 0x7FFFFFFF;
const int mod = 1e8 + 7;
const int Max = 1e9;
const int maxn = 1e3 + 10;
int T, n, m, x, y, sum;
int f[maxn][maxn], a[maxn][maxn];

int gcd(int x, int y)
{
    if (a[x][y]) return a[x][y];
    return a[x][y] = (x%y ? gcd(y, x%y) : y);
}

int main()
{
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d", &n);
        for (int i = 0; i <= 1000; i++) f[0][i] = 0;
        for (int i = 1; i <= n; i++)
        {
            scanf("%d", &x);
            for (int j = 1; j <= 1000; j++)
            {
                f[i][j] = f[i - 1][j];
                if (f[i - 1][j])
                {
                    (f[i][gcd(j, x)] += f[i - 1][j]) %= mod;
                }
            }
            f[i][x] = (f[i][x] + 1) % mod;
        }
        sum = 0;
        for (int i = 1; i <= 1000; i++) (sum += (LL)f[n][i] * i%mod) %= mod;
        printf("%d\n", sum);
    }
    return 0;
}


 

你可能感兴趣的:(HDU 5656 CA Loves GCD)