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;
    }
  • 相关阅读:
    做程序员,我骄傲了吗?
    乐字节Java面向对象三大特性以及Java多态
    Java为什么有前途?什么人适合学Java?
    Java新手从入门到精通的学习建议
    Java变量与数据类型之二:Java常量与变量
    模块化、结构化的代码,程序员正讲述着人生
    乐字节Java变量与数据类型之一:Java编程规范,关键字与标识符
    乐字节Java学习课程-path环境变量的作用与配置
    我英语不好,能学会编程吗?
    为什么欧拉图要用栈存然后逆着输出
  • 原文地址:https://www.cnblogs.com/01world/p/5651236.html
Copyright © 2011-2022 走看看