• 递推DP URAL 1009 K-based Numbers


    题目传送门

    题意:n位数,k进制,求个数
    分析:dp[i][j] 表示i位数,当前数字为j的个数;若j==0,不加dp[i-1][0];

    代码1:

    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    
    const int MAXN = 22;
    const int INF = 0x3f3f3f3f;
    long long dp[MAXN][MAXN];
    
    int main(void)        //URAL 1009 K-based Numbers
    {
        //freopen ("B.in", "r", stdin);
    
        int n, k;
        while (scanf ("%d%d", &n, &k) == 2)
        {
            memset (dp, 0, sizeof (dp));
            for (int i=1; i<k; ++i)    dp[1][i] = 1;
            for (int i=2; i<=n; ++i)
            {
                for (int j=0; j<k; ++j)
                {
                    if (!j)
                        for (int l=1; l<k; ++l)    dp[i][j] += dp[i-1][l];
                    else
                        for (int l=0; l<k; ++l)    dp[i][j] += dp[i-1][l];
                }
            }
    
            long long ans = 0;
            for (int i=0; i<k; ++i)    ans += dp[n][i];
            printf ("%I64d
    ", ans);
        }
    
        return 0;
    }

    代码2(空间优化):

    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    
    const int MAXN = 22;
    const int INF = 0x3f3f3f3f;
    long long dp[MAXN];
    
    int main(void)        //URAL 1009 K-based Numbers
    {
        //freopen ("B.in", "r", stdin);
    
        int n, k;
        while (scanf ("%d%d", &n, &k) == 2)
        {
            memset (dp, 0, sizeof (dp));
            
            dp[0] = 1;    dp[1] = k - 1;
            for (int i=2; i<=n; ++i)
            {
                dp[i] = (dp[i-1] + dp[i-2]) * (k-1);
            }
    
            printf ("%I64d
    ", dp[n]);
        }
    
        return 0;
    }
    
    编译人生,运行世界!
  • 相关阅读:
    Redis使用详细教程
    Web API 强势入门指南
    log4net
    ASP.NET Web API——选择Web API还是WCF
    Hadoop RPC机制
    力扣算法:每日温度
    力扣算法:完全平方数
    力扣算法:岛屿数量
    面试总结二
    面试总结
  • 原文地址:https://www.cnblogs.com/Running-Time/p/4482702.html
Copyright © 2020-2023  润新知