PAT (Advanced Level) Practice 1049 Counting Ones (30 分)

Posted Keep--Silent

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT (Advanced Level) Practice 1049 Counting Ones (30 分)相关的知识,希望对你有一定的参考价值。

The task is simple: given any positive integer N, you are supposed to count the total number of 1’s in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1’s in 1, 10, 11, and 12.

Input Specification:
Each input file contains one test case which gives the positive N (≤230).

Output Specification:
For each test case, print the number of 1’s in one line.

Sample Input:
12

Sample Output:
5

题目大意,从1到n,求每个数的1的个数之和
解决:数位dp
从首位往后,每次选1或者不选1,选1则个数加一,不选则保留当前个数。

#include <bits/stdc++.h>
using namespace std;
int num[SIZE];
int ans;
int dfs(int pos,bool limit,int cnt) {
	int ans=0;
	if(pos<0) {
		return cnt;
	}
	//if(limit==0)
	int up=limit?num[pos]:9;
	if(up==0)ans+=dfs(pos-1,limit,cnt);
	if(up==1){
		//选0和选1 
		ans+=dfs(pos-1,false,cnt);
		ans+=dfs(pos-1,limit&&1==num[pos],cnt+1);
	}
	if(up>=2){
		ans+=dfs(pos-1,false,cnt+1);//选1 
		ans+=(up-1)*dfs(pos-1,false,cnt);//选0,2,3..up-1 
		ans+=dfs(pos-1,limit,cnt);//选up 
	}
	return ans;
}
int main() {
	int n,m,k=0,i,j,x,pot;
	cin>>n;
	x=n;
	while(x) {
		num[k++]=x%10;
		x/=10;
	}
	cout<<dfs(k-1,true,0)<<endl;
	return 0;
}

pos是第几位,limit是判断是否前面的每一位都是上界,cnt是前面1的个数。
数位dp的关键:
ans+=dfs(pos-1,limit && i==a[pos]) ;

以上是关于PAT (Advanced Level) Practice 1049 Counting Ones (30 分)的主要内容,如果未能解决你的问题,请参考以下文章