zoj3662 Math Magic(数论+dp)

Math Magic

Time Limit: 3 Seconds       Memory Limit: 32768 KB

Yesterday, my teacher taught us about math: +, -, *, /, GCD, LCM... As you know, LCM (Least common multiple) of two positive numbers can be solved easily because of a * b = GCD (a, b) * LCM (a, b).

In class, I raised a new idea: "how to calculate the LCM of K numbers". It's also an easy problem indeed, which only cost me 1 minute to solve it. I raised my hand and told teacher about my outstanding algorithm. Teacher just smiled and smiled...

After class, my teacher gave me a new problem and he wanted me solve it in 1 minute, too. If we know three parameters N, M, K, and two equations:

1. SUM (A1, A2, ..., Ai, Ai+1,..., AK) = N 
2. LCM (A1, A2, ..., Ai, Ai+1,..., AK) = M

Can you calculate how many kinds of solutions are there for Ai (Ai are all positive numbers). I began to roll cold sweat but teacher just smiled and smiled.

Can you solve this problem in 1 minute?

Input

There are multiple test cases.

Each test case contains three integers N, M, K. (1 ≤ N, M ≤ 1,000, 1 ≤ K ≤ 100)

Output

For each test case, output an integer indicating the number of solution modulo 1,000,000,007(1e9 + 7).

You can get more details in the sample and hint below.

Sample Input
4 2 2
3 2 2
Sample Output
1
2
Hint

The first test case: the only solution is (2, 2).

The second test case: the solution are (1, 2) and (2, 1).

预处理出LCM[1000][1000]来。

dp[now][i][j]表示当前状态下,和为i,LCM为j的解的个数。递推K次就出答案了。

#include<stdio.h>
int sum[2][1010][1010],lcm[1010][1010];

int gcd(int x,int y)//最大公约数
{
	int a;
	if(a=x%y)
		gcd(y,a);
	else return y;
}
int main()
{
	int i,j,p,k,n,m,t,s[1000],count,c,temp1,temp2;
	for(i=1;i<=1000;i++)
	{
		for(j=i+1;j<=1000;j++)//任意两个最小公倍数
			lcm[i][j]=lcm[j][i]=i*j/gcd(j,i);
		lcm[i][i]=i;
	}
	while(scanf("%d%d%d",&n,&m,&k)!=EOF)
	{
		for(i=1,j=0;i<=m;i++)
			if(m%i==0)//找出能被m整除的数
			{
				s[j++]=i;
			}
		count=j;
		p=0;
		for(i=0;i<=n;i++)//初始化
			for(j=0;j<count;j++)
				sum[p][i][s[j]]=0;
		sum[p][0][1]=1;
		for(t=1;t<=k;t++)//个数
		{
			p^=1;
			for(i=0;i<=n;i++)//初始化
				for(j=0;j<count;j++)
					sum[p][i][s[j]]=0;
			for(i=t-1;i<=n;i++)//几个数之和
				for(j=0;j<count;j++)//最小公倍数为j
				{
					if(sum[p^1][i][s[j]]==0)//没有这个状态
						continue;
					for(c=0;c<count;c++)
					{
						temp1=s[c]+i;//和
						temp2=lcm[s[j]][s[c]];//最小公倍数
						if(temp1>n||m%temp2)//和已经超过了n或者最小公倍数比m大
							continue;
						sum[p][temp1][temp2]+=sum[p^1][i][s[j]];
						sum[p][temp1][temp2]%=1000000007;
					}
				}
		}
		printf("%d\n",sum[p][n][m]);
	}
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值