Lucky Sum (codeforces)4 7的故事

Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + … + next(r - 1) + next®. Help him solve this problem.

Input
The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits.

Output
In the single line print the only number — the sum next(l) + next(l + 1) + … + next(r - 1) + next®.

Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
Input
2 7
Output
33
Input
7 7
Output
7
Note
In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33

In the second sample: next(7) = 7。
在国庆节这样的日子竟然要我在家里敲代码。哇呀呀。。
第一眼看到这个题,题意很好懂无非就是求在区间(l,r)大于等于数n的最小的由4和7组成的数(看一下note就可以懂啦)。第一眼想到的是暴力(毕竟我是弱鸡)。但是实现起来太困难,而且很不现实
,会超时的 。然后转换一下思路,首先写了写有4和7组成的数字,4,7,44,47,74,77,,,,这里就可以看到规律了。二个一分组,都是前一组的乘以十加上4或7得来的。在这里我们先把10^10以内的幸运数存起来,然后求出区间端点的幸运值,做差就可以啦。
代码给上:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#define ll long long
using namespace std;

const int maxx=1050;
ll a[maxx];

void init()
{
	a[1]=4;
	a[2]=7;
	int count=3;
	for(int i=1;i<512;i++)
	{
		a[count++]=a[i]*10+4;
		a[count++]=a[i]*10+7;
	}
}

ll cnm(ll n)
{
	if(n==0) return 0;
	ll ans=0;
	for(int i=1;i<=1024;i++)
	{
		if(a[i]<n)
		ans+=a[i]*(a[i]-a[i-1]);
		else 
		{
			ans+=a[i]*(n-a[i-1]);
			break;
		}
	}
	return ans;
}

int main()
{
	init();
	int l,r;
	while(scanf("%d%d",&l,&r)!=EOF)
	{
		printf("%I64d\n",cnm(r)-cnm(l-1));
	}
	return 0;
}

每天加油a啊,(o)/~。

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/82924395
今日推荐