51nod 1009数字1的数量(数位dp)

https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1009&judgeId=580006

1009 数字1的数量 

基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题

 收藏

 关注

给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的个数。

例如:n = 12,包含了5个1。1,10,12共包含3个1,11包含2个1,总共5个1。

Input

输入N(1 <= N <= 10^9)

Output

输出包含1的个数

Input示例

12

Output示例

扫描二维码关注公众号,回复: 2365796 查看本文章
5

听学长的话在刷51nod的题,题都基本上不会,只能硬着头皮写......不知道过几天会怎么样如果刷完就换poj把....啥都不会唉....

#include<iostream>
#include<string.h>
#include<algorithm>
#include<vector>
#include<stdio.h>
#include<map>
#include<math.h>
#include<stack>
#define inf 0x3f3f3f
#define ll long long
#define maxn 505
using namespace std;
//ll a[maxn][maxn];
ll dp[maxn][maxn];//第0到i位数值为j的1的个数 
int n;
ll a[100];//表示n第i位的数 
int dfs(int pos,int num,bool limit)
{
	if(pos==0)return 0;
	if(!limit&&dp[pos][num]!=-1)//记忆化 
		return dp[pos][num];
	int  ans=0;
	int k=limit?a[pos-1]:9;
	if(num==1)
	{
		if(limit)
		{
			for(int i=pos-1;i>=1;i--)//如果是1234  它是由234+1000个有1的个数 
			ans+=a[i]*pow(10,i-1);
			ans++;
		}
		else
		{
			ans+=pow(10,pos-1);//如果为1000的话直接就是1000以内1的个数; 
		}
	}
	for(int i=0;i<=k;i++)
	{
		ans+=dfs(pos-1,i,limit&&i==a[pos-1]);
	}
	if(!limit)
	{
		dp[pos][num]=ans;
	}
	return ans;
	
}
int solve(int x)
{
	int pos=0;
	while(x)
	{
		a[++pos]=x%10;
		x/=10;
	}
	return dfs(pos+1,-1,true);
}
int main()
{
    cin>>n;
    memset(dp,-1,sizeof(dp));
    cout<<solve(n);
  
  	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41453511/article/details/81188520