hdu 5656 递推

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

题意:求所有子集的gcd的和。
分析:
求所有子集那肯定是不行的,因为要求的是所有子集的gcd的和,那么可以求出gcd为i的集合数sum[i]。然后就是求和sum[i]*i。这样就解决了。
对于如何求sum[i]。想法当然是枚举所有子集然后求出他们的gcd,然后对应的gcd数加起来啊。因为数太大,无法这样枚举,因为子集的gcd(1,2,3,..i)和gcd(1,2,3…i,i+1)相比,只是增加了i+1这个数,那么gcd(1..i+1)=gcd(1…i+1)+gcd(gcd(1…i),i+1)。所以递推公式就出来了,因为gcd(1…i)在前面已经求出来了,这样问题就可以解决了。而gcd(1…i)需要保存起来,避免重复计算。我可能描述的不是很清楚,可以参考这篇博客,讲的很详细的:http://blog.csdn.net/angon823/article/details/51046825
PS:因为时限是3000MS,而枚举的复杂度是O(N^2)(不考虑gcd),所以gcd不必优化,如果时限是1000MS,那么gcd就要就要预处理一下,否则很容易超时。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<vector>
using namespace std;
#define mp make_pair
#define pb push_back
const int mod=100000007;
const int N=1e5+5;
typedef  unsigned long long int LL;
typedef pair<int,int>pii;
int gcd(int a,int b){return b==0?a:gcd(b,a%b);}
int n,sum[1111];
int main()
{
    int T; scanf("%d",&T);
    while(T--){
        memset(sum,0,sizeof(sum));
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            int x; scanf("%d",&x);
            for(int j=1;j<=1000;j++){
                if(sum[j]){
                    int t=gcd(j,x);
                    sum[t]=(sum[t]+sum[j])%mod;
                }
            }
            sum[x]++;
        }
        LL ans=0;
        for(int i=1;i<=1000;i++){
            ans=(ans+(LL)i*sum[i]%mod)%mod;
        }
        cout<<ans<<endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/01world/p/5651236.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值