spoj CPCRC1C(数位dp)

CPCRC1C - Sum of Digits


Majid is a 3rd-grade elementary student and quite well in mathematics. Once, Majid's teacher asked him to calculate the sum of numbers 1 through n.

Majid quickly answered, and his teacher made him another challenge. He asked Majid to calculate the sum of the digits of numbers 1 through n.

Majid did finally find the solution. Now it is your turn, can you find a solution?

Input

Two space-separated integers 0 <= a <= b <= 109.

Program terminates if a and b are -1.

Output

The sum of the digits of numbers a through b.

Example

Input:
1 10
100 777
-1 -1

Output:
46
8655

#include<bits/stdc++.h>
using namespace std;
long long f(long long x)
{
    long long ans=0;
    while(x!=0)
    {
        ans+=x%10;
        x/=10;
    }
    return ans;
}
long long dfs(long long a,long long b,long long t)
{
	if(a==0)
		a=1;
	if(b==0)
		return 0;
	if(a>b)
		return 0;
    long long sum=0;
    long long a1=((a-1)/10+1)*10;
    long long b1=b/10*10;
    if(a1>b1)
    {
    	for(long long i=a;i<=b;i++)
    		sum+=f(i)*t;
    	return sum;
	}
    for(long long i=a;i<=b;i++)
    {
        if(i%10==0)
        {
            sum+=45*(b1-a1)/10;
            i=b1;
        }
        else
            sum+=i%10;
    }
    long long l=a1-a;long long r=b%10+1;
    long long ans=(sum+l*f(a/10)+r*f(b/10))*t+dfs(l==0?a/10:a/10+1,r==0?b/10:b/10-1,t*10);
    return ans;
}
int main()
{
    long long a,b;
    while(1)
    {
        scanf("%lld%lld",&a,&b);
        if(a==-1&&b==-1)
        	break;
        printf("%lld\n",dfs(a,b,1));
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值