BestCoder Round #78 (div.2)1002 CA Loves GCD

CA Loves GCD

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


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
 

DP问题从来都是一项玄学,很多情况下用DP一下就能解决的问题,但往往我们就是想不到,此题就是一个DP问题,当然在比赛的讨论中有人说这题暴力也能过……我相信这题暴力应该是过不了终端的。

首先我们先看看官方的题解:

1002

By YJQ 我们令dp[i][j]表示在前i个数中,选出若干个数使得它们的gcd为j的方案数,于是只需要枚举第i+1个数是否被选中来转移就可以了

令第i+1个数为v,当考虑dp[i][j]的时候,我们令$dp[i+1][j] += dp[i]j,dp[i+1][gcd(j,v)] += dp[i]j

复杂度O(N*MaxV) MaxV 为出现过的数的最大值

其实有O(MaxV *log(MaxV))的做法,我们考虑记f[i]表示从这些数中选择若干个数,使得他们的gcd是i的倍数的方案数。假如有K个数是i的倍数,则f[i]=2^K-1,再用g[i]表示从这些数中选择若干个数,使得他们的gcd是i的方案数,则g[i]=f[i] - g[j] (对于所有j是i的倍数)。

由调和级数可以得到复杂度为O(MaxV *log(MaxV))


题解上写的很清楚,小编在这里解释一下状态转移方程的含义:dp[i+1][j] 如果不取a[i+1]这个数,那么dp[i][j]就可以达到dp[i+1][j]的状态,如果取到了a[i+1]这个数,那么dp[i][j]就可以达到dp[i+1][gcd(j,a[i+1])]的状态。这就是状态的转移方程,为了防止超时,可以再对1000*1000这个范围内对gcd进行预处理一下。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000+5;
const int MOD = 100000007;
int a[maxn],dp[maxn][maxn];
int GCD[maxn][maxn];
int gcd(int x,int y)
{
	if(x == 0) return y;
	return gcd(y%x,x);
}
int main()
{
	for(int i=0; i<=1000; i++)
		for(int j=0; j<=1000; j++)
			GCD[i][j] = gcd(i,j);
	int T,n;
	scanf("%d",&T);
	while(T--)
	{
		memset(dp,0,sizeof(dp));
		scanf("%d",&n);
		int Max = 0;
		for(int i=1; i<=n; i++)
		{
			scanf("%d",&a[i]);
			Max = max(a[i],Max);
		}
		dp[0][0] = 1;
		for(int i=0; i<n; i++)
		{
			for(int j=0; j<=Max; j++)
			{
				if(dp[i][j])
				{
					(dp[i+1][j] += dp[i][j]) %= MOD;
					(dp[i+1][GCD[j][a[i+1]]] += dp[i][j]) %= MOD;
				}
			}
		}
		int ans = 0;
		for(int i=0; i<=Max; i++)
			ans = (ans + ((long long)dp[n][i])*i%MOD) % MOD;
		printf("%d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值