博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数位dp(求1-n中数字1出现的个数)
阅读量:6981 次
发布时间:2019-06-27

本文共 1358 字,大约阅读时间需要 4 分钟。

题意:求1-n的n个数字中1出现的个数。

解法:数位dp,dp[pre][now][equa] 记录着第pre位为now,equa表示前边是否有降数字(即后边可不能够任意取,true为没降,true为已降);常规的记忆化搜索

代码:

/******************************************************* author:xiefubao*******************************************************/#pragma comment(linker, "/STACK:102400000,102400000")#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//freopen ("in.txt" , "r" , stdin);using namespace std;#define eps 1e-8const double pi=acos(-1.0);typedef long long LL;const int Max=10100;const int INF=1000000007;int fac[10];void init(){ fac[0]=1; fac[1]=1; for(int i=2; i<10; i++) fac[i]=fac[i-1]*10;}char s[20];int dp[20][20][2];int n;int num[20];int dfs(int pre,int now,int equa){ if(pre==0) return now==1; if(dp[pre][now][equa]!=-1) return dp[pre][now][equa]; int ans=0; if(now==1&&!equa) ans+=fac[pre+1]; if(now==1&&equa) ans+=n%fac[pre+1]+1; int en=equa?num[pre-1]:9; for(int i=0;i<=en;i++) ans+=dfs(pre-1,i,equa&&i==num[pre-1]); return dp[pre][now][equa]=ans;}int getans(int t){ int p=0; memset(dp,-1,sizeof dp); while(t) { num[p++]=t%10; t/=10; } int ans=0; for(int i=0; i<=num[p-1]; i++) { ans+=dfs(p-1,i,i==num[p-1]); } return ans;}int main(){ init(); while(cin>>n) { printf("%d\n",getans(n)); } return 0;}

转载地址:http://uqcpl.baihongyu.com/

你可能感兴趣的文章
ajax实现点击加载更多
查看>>
为什么JavaScript没有类而使用原型?——JavaScript语言特性来历
查看>>
TarsGo新版本发布,支持protobuf,zipkin和自定义插件
查看>>
Flutter 如何创建并发布 Plugin (VS Code + GitHub 发布)
查看>>
TableStore实战:GEO索引打造亿量级店铺搜索系统
查看>>
js的防抖和节流
查看>>
redis学与思系列(2)
查看>>
学习springBoot(11)shiro安全框架
查看>>
c++那些事儿11 0 STL List
查看>>
问题记录——跨域
查看>>
PHP7.3即将到来,快来了解一下新特性吧
查看>>
1月9日云栖精选夜读:场景化封装,一站式使用,普惠AI集成 ——阿里云发布智能媒体管理产品...
查看>>
Java Servlet Filter 详解
查看>>
区块链走向何方,或许从美国证劵史可以得到答案
查看>>
Golang web之http标准库简析
查看>>
项目冷启动,搭建MVP产品框架
查看>>
Python爬取网易云音乐歌单歌曲
查看>>
掘金markdown笔记快捷键
查看>>
[译] 为什么加密货币泡沫会破裂?
查看>>
Python 发送邮件
查看>>