基准时间限制:1 秒 空间限制:131072 KB 分值: 10
难度:2级算法题
给出一段区间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
思路:
和1009类型相同,但是这个题的变化在于数字0的数量,因为数字0不可以出现在首位,所以在0的时候必须重新去重首位为0的情况
#include <iostream>
#include <stdio.h>
using namespace std;
typedef long long ll;
long long dp[20];
void solve(long long n,int x,int as)
{
long long count = 0;
long long i = 1;
long long current = 0,after = 0,before = 0;
while((n / i) != 0)
{
current = (n / i) % 10;
before = n / (i * 10);
after = n - (n / i) * i;
if (current > x)
count = count + (before + 1) * i;
else if (current <x)
count = count + before * i;
else if(current == x)
count = count + before * i + after + 1;
i = i * 10;
}
if (x == 0)
{
long long m = 1;
long long num=n;
while (num != 0)
{
count -= m;
m = m * 10;
num = num / 10;
}
}
if(as==1)
dp[x]=count;
else
dp[x]-=count;
}
int main()
{
long long a,b;
cin>>a>>b;
for(int i=0; i<=9; i++)
solve(b,i,1);
for(int i=0; i<=9; i++)
solve(a-1,i,0);
for(int i=0; i<=9; i++)
cout<<dp[i]<<endl;
return 0;
}