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 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). Contest: The 2012 ACM-ICPC Asia Changchun Regional Contest
|
题意:给定数字N和M,K,求K个数字和为N并且最小公倍数为M的方案数。
思路:最小公倍数为M的话那些数字肯定就是M的因子了,我们只需要把M的因子都挑出来,然后将其作为物品进行背包即可,但是有个问题,不做处理直接存的话是会爆内存的,想一想背包九讲当中01背包二维降为一位的想法,挑选的前i个数是由前i-1个数转移来的,那么就可以用滚动数组来进行背包了。dp[i][j][k]表示前i个数字和为j最小公倍数为k的方案数。
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
const int mod=1e9+7;
int dp[2][1005][1005],LCM[1005][1005],num[105];
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
int lcm(int a,int b)
{
return a/gcd(a,b)*b;
}
int main()
{
int n,m,k;
for(int i=1;i<=1000;i++)
for(int j=1;j<=1000;j++)
LCM[i][j]=lcm(i,j);
while(scanf("%d%d%d",&n,&m,&k)!=EOF)
{
int cnt=0;
for(int i=1;i<=m;i++)
{
if(m%i==0)
num[cnt++]=i;
}
int now=0;
memset(dp,0,sizeof(dp));
dp[now][0][1]=1;
for(int t=1;t<=k;t++)
{
now=now^1;
for(int i=0;i<=n;i++)
for(int j=0;j<cnt;j++)
dp[now][i][num[j]]=0;
for(int i=0;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(x>n||m%y!=0) continue;
dp[now][x][y]+=dp[now^1][i][num[j]];
dp[now][x][y]%=mod;
}
}
}
}
printf("%d\n",dp[now][n][m]);
}
return 0;
}