【51nod-1042】数字0-9的数量
给出一段区间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 <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL bit[20], dp[20][20];//dp[i][j]当前位置前面有j个1的总数
LL dfs0(LL len, bool lead, bool lim, LL num, LL base)//base = 0特殊处理前导0
{
if(len == 0) return num;
if(!lim && !lead && dp[len][num]!= -1) return dp[len][num];
LL up = lim? bit[len] : 9;
LL ans = 0;
for(LL i = 0; i <= up; i++)
{
ans += dfs0(len - 1, lead && i == 0, lim && i == up, num + (i==base && !lead), base);
}
if(!lim && !lead) dp[len][num] = ans;
return ans;
}
LL dfs(LL len, bool lim, LL num, LL base)//base:1-9
{
if(len == 0) return num;
if(!lim && dp[len][num]!= -1) return dp[len][num];
LL up = lim? bit[len] : 9;
LL ans = 0;
for(LL i = 0; i <= up; i++)
{
ans += dfs(len - 1, lim && i == up, num + (i==base), base);
}
if(!lim) dp[len][num] = ans;
return ans;
}
LL sol(LL n, LL base)
{
LL len = 0;
while(n)
{
bit[++len] = n % 10;
n /= 10;
}
if(base == 0)
return dfs0(len, 1, 1, 0, base);
else
return dfs(len, 1, 0, base);
}
int main()
{
LL n, m;
cin>>n>>m;
for(int i = 0; i <= 9; i++)
{
memset(dp, -1, sizeof dp);
printf("%lld\n", sol(m, i) - sol(n-1, i));
}
return 0;
}