题目大意:
给定两个整数 ,求出区间 中每个数的数字和的和。
7 倍经验:
UVA1640-统计问题 The Counting Problem
思路:
这是一道经典的数位 dp 题目,想详细了解请移步 OI-Wiki。其中所求的数字 和的和也就是 。( 代表在区间 里数字 出现的次数)
Code:
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<set>
#include<cstdlib>
#define ll long long
#define ull unsigned long long
using namespace std;
const int N=30;
ll t,x,y,ans;
ll a[N];
ll power(ll x)//求 10 的 x 次方
{
ll res=1;
while(x--) res*=10;
return res;
}
ll f(ll l,ll r)
{
ll res=0;
for(int i=l;i>=r;i--)
{
res=res*10+a[i];
}
return res;
}
ll count(ll n,ll x)//核心代码
{
if(n==0) return 0;
ll k=0,t=n;
while(t)
{
a[++k]=t%10;
t/=10;
}
ll ans=0;
for(int i=k-!x;i>0;i--)
{
if(i!=k) ans+=(f(k,i+1)-!x)*power(i-1);
if(x==a[i]) ans+=(f(i-1,1)+1);
else if(x<a[i]) ans+=power(i-1);
}
return ans;
}
int main()
{
while(cin>>x>>y&&x!=0&&y!=0)
{
ans=0;
for(int i=1;i<=9;i++)
{
ans+=(count(y,i)-count(x-1,i))*i;//ans累加每个数字的数字和
}
cout<<ans<<endl;
}
return 0;
}