给出一段区间a-b,统计这个区间内0-9出现的次数。
比如 10-19,1出现11次(10,11,12,13,14,15,16,17,18,19,其中11包括2个1),其余数字各出现1次。
Input
两个数a,b(1 <= a <= b <= 10^18)
OutPut
输出共10行,分别是0-9出现的次数
Input示例
10 19
Output示例
1 11 1 1 1 1 1 1 1 1
虽然之前做过这道题,但这次还是花了近俩小时调通的错误,蛋疼。。。, 代码没有简化,也懒得去弄了,思路算是理顺了。
#include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <algorithm> using namespace std; typedef long long ll; ll base[20]; ll num[19]; void init() { base[0] = 1; for(int i = 1; i < 20; ++i) { base[i] = 10 * base[i-1]; } num[0] = 0; num[1] = 1; for(int i = 2; i < 19; ++i) { num[i] = 10 * num[i-1] + base[i-1]; } } ll ans[2][10]; void cal_1_9(ll a, int id) { int pos = 0; while(base[pos] <= a) pos++; pos--; while(a) { for(int i = 1; i <= 9; ++i) { ans[id][i] += (a/base[pos])*num[pos]; } for(int i = 1; i < a/base[pos]; ++i) { ans[id][i] += base[pos]; } ans[id][a/base[pos]] += (a%base[pos]+1); a = a % base[pos]; while(pos >= 0 && base[pos] > a) pos--; } return ; } int cal_digit(ll x) { int ret = 0; while(x) { ret++; x /= 10; } return ret; } void cal_0(ll a, int id) { if(a == 0) { ans[id][0] = 1; return ; } int pos = 0; while(base[pos] <= a) pos++; pos--; if(pos > 0) { ans[id][0] -= (pos - 1); ll t = 9; for(int i = 1; i < pos; ++i) { ans[id][0] -= (pos - i) * t; t *= 10; } } bool first = true; while(a) { if(pos == 0) { ans[id][0] += 1; } ans[id][0] += (a/base[pos])*num[pos]; if(!first && pos > 0) { ans[id][0] += base[pos]; } int bit = cal_digit(a%base[pos]); if(pos > bit) { ans[id][0] += (pos-cal_digit(a%base[pos]))*(a%base[pos]+1); } a = a % base[pos]; while(pos >= 0 && base[pos] > a) pos--; first = false; } return ; } int main() { init(); memset(ans, 0, sizeof(ans)); ll a, b; cin >> a >> b; cal_1_9(b, 0); cal_1_9(a-1, 1); cal_0(b, 0); cal_0(a-1, 1); for(int i = 0; i <= 9; ++i) { cout << ans[0][i] - ans[1][i] << endl; } return 0; }