zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    python 学习笔记 数值型(1)
    python 学习笔记 标识符和变量(3)
    python 学习笔记 字符串(2)
    jsp+servlet+javaBean+Dao
    面试被问到岗时间,是越快越好吗?
    有赞多平台推广接入与测试
    HTTPS 加密、证书、签名与握手
    开发到底要不要自己做测试?
    我也曾找不到工作
    世界第三大浏览器正在消亡
  • 原文地址:https://www.cnblogs.com/01world/p/5651236.html
Copyright © 2011-2022 走看看