Description
Given two integers a and b, we write the numbers between a and b, inclusive, in a list. Your task is to calculate the number of occurrences of each digit. For example, if a = 1024 and b = 1032, the list will bethere are ten 0's in the list, ten 1's, seven 2's, three 3's, and etc.
Input
The input consists of up to 500 lines. Each line contains two numbers a and b where 0 < a, b < 100000000. The input is terminated by a line `0 0', which is not considered as part of the input.Output
For each pair of input, output a line containing ten numbers separated by single spaces. The first number is the number of occurrences of the digit 0, the second is the number of occurrences of the digit 1, etc.Sample Input
1 10 44 497 346 542 1199 1748 1496 1403 1004 503 1714 190 1317 854 1976 494 1001 1960 0 0
Sample Output
1 2 1 1 1 1 1 1 1 1 85 185 185 185 190 96 96 96 95 93 40 40 40 93 136 82 40 40 40 40 115 666 215 215 214 205 205 154 105 106 16 113 19 20 114 20 20 19 19 16 107 105 100 101 101 197 200 200 200 200 413 1133 503 503 503 502 502 417 402 412 196 512 186 104 87 93 97 97 142 196 398 1375 398 398 405 499 499 495 488 471 294 1256 296 296 296 296 287 286 286 247
题目大意:给定一系列数字对(l,r),统计l到r之间每个数字出现次数。(注意l可能比r大,要调整一下,被坑掉好几发呜呜呜)
思路:很简单就是一个数位dp,dp[x][v][now]表示取到第x位为止,数字v取了now个之后的结果。因为当前导零和最大限制不存在的时候,同样的x,v,now不管前缀是怎么取得,都可以保证后面的搜索结果是相同的,所以取这样的状态就好了。(和传统的数位dp有一点点不同,卡了半个多小时看了眼题解才恍然大悟)。
下附代码:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #define ll long long 5 using namespace std; 6 int cnt[30]; 7 ll l,r,dp[30][12][50],ans[3][11]; 8 ll dfs(int x,int v,ll now,int jb,int lz){ 9 if (!x) { 10 return now; 11 } 12 if (!jb && !lz && dp[x][v][now]!=-1) return dp[x][v][now]; 13 int maxx; 14 if (jb) maxx=cnt[x]; 15 else maxx=9; 16 ll ret=0,t=0; 17 for (int i=0; i<=maxx; i++){ 18 if (v!=i) t=now; 19 else { 20 if (v==0) 21 if (!lz) t=now+1; 22 else t=0; 23 else t=now+1; 24 } 25 ret=ret+dfs(x-1,v,t,jb && (i==maxx), lz && i==0); 26 } 27 if (!jb && !lz) dp[x][v][now]=ret; 28 return ret; 29 } 30 int main(){ 31 memset(dp,-1,sizeof(dp)); 32 while (scanf("%lld%lld",&l,&r),l+r>0){ 33 if (l>r) swap(l,r); 34 l--; 35 int len=0; 36 while (l){ 37 cnt[++len]=l%10; 38 l/=10; 39 } 40 for (int i=0; i<=9; i++) ans[1][i]=dfs(len,i,0,1,1); 41 len=0; 42 while (r){ 43 cnt[++len]=r%10; 44 r/=10; 45 } 46 for (int i=0; i<=9; i++) ans[2][i]=dfs(len,i,0,1,1); 47 printf("%lld",ans[2][0]-ans[1][0]); 48 for (int i=1; i<=9; i++) printf(" %lld",ans[2][i]-ans[1][i]); 49 printf("\n"); 50 } 51 }View Code