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)/~。