題目鏈接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3662點擊打開鏈接
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
給出n,m,k;
問和爲n,lcm爲m,的k個數的情況個數mod1e9+7
由於內存和空間的限制 1000*1000*100開不出來 因此在lcm尋找突破口
得先知道一個東西:
定義x爲k個數的lcm k個數中的某些數的lcm是x的因子
這樣一來我們就能對m的因子進行枚舉 把他們當做物品並離散化(節約空間)
同時 因爲和與lcm與個數間沒有關係 因此可以把個數放在第一層循環 用滾動數組進行dp
因爲無論對物品怎麼lcm都是m的因子 所以接下來就是完全揹包的操作了
提前開個數組對lcm結果預處理 可優化時間
#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
int dp[2][1111][1111];
int __lcm(int a,int b)
{
return a*b/__gcd(a,b);
}
vector<int>s;
int lcm[1111][1111];
int main()
{
for(int i=1;i<=1000;i++)
{
for(int j=1;j<=1000;j++)
lcm[i][j]=__lcm(i,j);
}
int n,m,k;
while(~scanf("%d%d%d",&n,&m,&k))
{
s.clear();
for(int i=1;i<=m;i++)
{
if(m%i==0)
{
s.push_back(i);
}
}
int len=s.size();
memset(dp,0,sizeof(dp));
int flag=0;
dp[0][0][1]=1;
for(int p=1;p<=k;p++)
{
flag^=1;
for(int i=0;i<=n;i++)
for(int j=0;j<len;j++)
dp[flag][i][s[j]]=0;
for(int i=0;i<len;i++)
{
for(int j=s[i];j<=n;j++)
{
for(int l=len-1;l>=0;l--)
{
if(lcm[s[l]][s[i]]<=m)
{
dp[flag][j][lcm[s[l]][s[i]]]=(dp[flag][j][lcm[s[l]][s[i]]]+dp[1-flag][j-s[i]][s[l]])%mod;
}
}
}
}
}
cout << dp[flag][n][m] <<endl;
}
}