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 }
  • 相关阅读:
    ccf I’m stuck!
    ccf 最大的矩形
    ccf ISBN号码
    ccf 出现次数最多的数
    ccf 相反数
    BestCoder Round #33
    15年3月CCF真题5-最小花费
    15年3月CCF真题4-网络延时
    15年3月CCF真题3-节日
    15年3月CCF真题2-数字排序
  • 原文地址:https://www.cnblogs.com/wangyiming/p/11483102.html
Copyright © 2011-2022 走看看