首页 > 技术文章 > HDU 5656

hsd- 2016-04-03 20:32 原文

CA Loves GCD

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 809    Accepted Submission(s): 283


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
 

 

Source
 
题意:给你 n 个数 求着n个数不同组合情况下的gcd之和
题解:dp[i][j] 代表 前i个数中的组合 使得gcd为j的个数
重在理解下面几句代码
int v=a[j+1];
dp[j+1][k]=(dp[j+1][k]+dp[j][k])%mod; // 前j+1个 gcd 组合为k的包括 dp[j][k]
 if(dp[j][k])
{
 int gg=gcd(k,v); 
 dp[j+1][gg]=(dp[j+1][gg]+dp[j][k])%mod;//若前j个gcd为k然后增加第j+1个a[j+1]得到gg  
                                                                //可知道dp[j+1][gg] 包括dp[j][k](前j个gcd为k)
}
 
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #include<map>
 6 #include<queue>
 7 #include<stack>
 8 #include<set>
 9 #define ll __int64
10 #define mod 100000007
11 using namespace std;
12 ll dp[1005][1005];
13 int  a[1005];
14 int maxn;
15 int t,n;
16 ll ans=0;
17 ll gcd(ll aa,ll bb)// 求解gcd
18 {
19     ll exm;
20     if(aa<bb)
21     {
22         exm=aa;
23         aa=bb;
24         bb=exm;
25     }
26     if(bb==0)
27         return aa;
28     gcd(bb,aa%bb);
29 }
30 int main()
31 {
32     while(scanf("%d",&t)!=EOF)
33     {
34         for(int i=1; i<=t; i++)
35     {
36         ans=0;
37         memset(dp,0,sizeof(dp));
38         memset(a,0,sizeof(a));
39         scanf("%d",&n);
40         maxn=-1;
41         for(int j=1; j<=n; j++)
42         {
43             scanf("%d",&a[j]);
44             if(a[j]>maxn)
45                 maxn=a[j];
46             dp[j][a[j]]=1;//初始化 只取第j个a[j]
47         }
48         for(int j=1; j<=n; j++)
49         {
50             int v=a[j+1];
51             for(int k=1; k<=maxn; k++)
52             {
53                 dp[j+1][k]=(dp[j+1][k]+dp[j][k])%mod;
54                 if(dp[j][k])
55                 {int gg=gcd(k,v);
56                     dp[j+1][gg]=(dp[j+1][gg]+dp[j][k])%mod;}
57             }
58         }
59         for(int j=1; j<=maxn; j++)
60             ans=(ans+j*dp[n][j])%mod;
61         printf("%I64d\n",ans);
62     }
63     }
64     return 0;
65 }

 

推荐阅读