http://acm.hdu.edu.cn/showproblem.php?pid=4427
Problem Description
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 (A
1, A
2, ..., A
i, A
i+1,..., A
K) = N
2. LCM (A
1, A
2, ..., A
i, A
i+1,..., A
K) = M
Can you calculate how many kinds of solutions are there for A
i (A
i 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(10
9 + 7).
You can get more details in the sample and hint below.
Sample Input
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).
解题思路:dp[i][j][k]表示长度为i和为j且最小公倍数为k的序列有多少种。防止超时用到了很多优化,详见代码注释。
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
const int MOD=1e9+7;
const int N=1050;
int dp[2][N][N],LCM[N][N],num[N];//dp[i][j][k]:长度为i,和为j,最小公倍数为k的种类有多少
int n,m,k;
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int lcm(int a,int b)
{
return a/gcd(a,b)*b;
}
int main()
{
for(int i=1;i<=1000;i++)//求1000内任意两个数的最小公倍数
for(int j=1;j<=1000;j++)
LCM[i][j]=lcm(i,j);
while(~scanf("%d%d%d",&n,&m,&k))
{
int cnt=0;
for(int i=1;i<=m;i++)//每一个Ai一定是m的因子,求出m的所有因子
if(m%i==0)
num[cnt++]=i;
int now=0;
for(int i=1;i<=n;i++)//滚动数组清零
for(int j=0;j<cnt;j++)
dp[now][i][num[j]]=0;
dp[now][0][1]=1;
for(int t=1;t<=k;t++)
{
now^=1;
for(int i=1;i<=n;i++)// 滚动数组清零
for(int j=0;j<cnt;j++)
dp[now][i][num[j]]=0;
for(int i=t-1;i<=n;i++)
for(int j=0;j<cnt;j++)
{
if(dp[now^1][i][num[j]]==0)//优化
continue;
for(int p=0;p<cnt;p++)
{
int x=i+num[p];
int y=LCM[num[j]][num[p]];
if(y>m||x>n)continue;//最小公倍数大于m,长度大于n,根本不用再往下计算
dp[now][x][y]+=dp[now^1][i][num[j]];
dp[now][x][y]%=MOD;
}
}
}
printf("%d\n",dp[now][n][m]);
}
return 0;
}