hdu4427——dp

题意:求满足要求的给定长度有序序列的个数:该序列内的所有数之和为n,最小公倍数为m。

首先明确该序列只能由m的因子构成。接下来就是一个比较平常的思路了:dp[i][j][k]表示长度为i,和为j,最小公倍数为k的序列的个数。开三维数组的话,空间不允许,可以用滚动数组,其实这题状态不难想,主要是要优化:要预处理出1000内任意两个数的最小公倍数,甚至memset都不能乱用,不然就会tle。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 1000 + 10;
const int mod = 1000000000 + 7;

int gcd(int a, int b)
{
    return (b == 0 ? a : gcd(b, a % b));
}

int dp[2][maxn][maxn];
int lcm[maxn][maxn], ll[maxn], n, m, k, cnt;
int now;

int main()
{
    freopen("in", "r", stdin);
    for(int i = 1; i <= 1000; ++i) for(int j = i; j <= 1000; ++j) lcm[i][j] = lcm[j][i] = (i * j) / gcd(i, j);
    while(~scanf("%d %d %d", &n, &m, &k))
    {
        cnt = 0;
        for(int i = 1; i <= m; ++i)
            if(m % i == 0) ll[cnt++] = i;
        now = 0;
        memset(dp[0], 0, sizeof(dp[0]));
        for(int i = 0; i < cnt; ++i) dp[now][ll[i]][ll[i]] = 1;
        for(int i = 1; i < k; ++i)
        {
            for(int a = i; a <= n; ++a)
                for(int b = 0; b < cnt; ++b)
                    dp[now ^ 1][a][ll[b]] = 0;
            for(int j = i; j < n; ++j)
            {
                for(int q = 0; q < cnt; ++q)
                {
                    int tmp1 = ll[q];
                    if(dp[now][j][tmp1] == 0) continue;
                    for(int p = 0; p < cnt; ++p)
                    {
                        int tmp2 = ll[p];
                        int lc = lcm[tmp1][tmp2];
                        if(j + tmp2 > n) break;
                        dp[now ^ 1][j + tmp2][lc] += dp[now][j][tmp1];
                        dp[now ^ 1][j + tmp2][lc] %= mod;
                    }
                }
            }
            now ^= 1;
        }
        printf("%d\n", dp[now][n][m]);
    }
    return 0;
}
/*
4 2 2
3 2 2

1
2
*/


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值