ZOJ - 3662 Math Magic(dp)

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3662点击打开链接

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

给出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;
    }
}


猜你喜欢

转载自blog.csdn.net/xuejye/article/details/80274337