zoukankan      html  css  js  c++  java
  • 51nod1009 数字1的数量

    思路:

    数位dp。

    实现:

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 class Solution
     4 {
     5 public:
     6     vector<int> preprocess(int x)
     7     {
     8         vector<int> res;
     9         while (x) { res.push_back(x % 10); x /= 10; }
    10         return res;
    11     }
    12     int dfs(vector<int>& a, int p, int cnt, bool u, vector<vector<int>>& dp)
    13     {
    14         if (p == -1) return cnt;
    15         if (!u && dp[p][cnt] != -1) return dp[p][cnt];
    16         int res = 0;
    17         int h = u ? a[p] : 9;
    18         for (int i = 0; i <= h; i++)
    19         {
    20             res += dfs(a, p - 1, cnt + (i == 1), u && (i == h), dp);
    21         }
    22         return u ? res : dp[p][cnt] = res;
    23     }
    24     int NumberOf1Between1AndN_Solution(int n)
    25     {
    26         vector<int> a = preprocess(n);
    27         int l = a.size();
    28         vector<vector<int>> dp(l, vector<int>(l + 1, -1));
    29         return dfs(a, l - 1, 0, true, dp);
    30     }
    31 };
    32 
    33 int main()
    34 {
    35     int n;
    36     while (cin >> n)
    37     {
    38         cout << Solution().NumberOf1Between1AndN_Solution(n) << endl;
    39     }
    40     return 0;
    41 }
  • 相关阅读:
    递归与分治4
    递归与分治3
    递归与分治2
    递归与分治1
    枚举与递推3
    枚举与递推2
    求编译器中数的最值(c++)
    移动小球链表实现
    阶乘的精确值
    while((c = getchar()) != EOF)(键盘输入问题)
  • 原文地址:https://www.cnblogs.com/wangyiming/p/11483102.html
Copyright © 2011-2022 走看看