*【CodeForces - 122C 】Lucky Sum (bfs记录状态,二分查找,有坑)(或分块)
題干:
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(r). 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(r).
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.
Examples
Input
2 7Output
33Input
7 7Output
7Note
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
解題報(bào)告:?
? ?這題不難發(fā)現(xiàn)是狀態(tài)的轉(zhuǎn)移,每一個(gè)狀態(tài)可以延伸到新的兩個(gè)狀態(tài),所以考慮bfs搜索一下,然后二分查找位置就可以暴力了。這題的一個(gè)坑點(diǎn)在于,能否發(fā)現(xiàn),當(dāng)st和ed是相等的時(shí)候就不能分區(qū)間這么看了,而應(yīng)該直接看這個(gè)區(qū)間。找個(gè)例子看啊:這種樣例很好找啊,比如1e9 1e9這個(gè)樣例。
AC代碼:
#include<bits/stdc++.h> #define ll long long using namespace std; ll b[100005]; int tot; void bfs() {priority_queue<ll,vector<ll>,greater<ll> > pq;tot = 0;b[++tot] = 4;pq.push(4);b[++tot] = 7;pq.push(7);while(!pq.empty()) {ll cur = pq.top();pq.pop();if(cur > (ll)1e12+7) return ;b[++tot] = cur*10+4;pq.push(b[tot]);b[++tot] = cur*10+7;pq.push(b[tot]);} } int main() {bfs();ll l,r;cin>>l>>r; // cout << b[tot] << endl;ll ans = 0;int st = lower_bound(b+1,b+tot+1,l) - b;int ed = lower_bound(b+1,b+tot+1,r) - b;if(ed > st) {ans += (b[st] - l + 1) * b[st];for(int i = st+1; i<ed; i++) {ans += (b[i] - b[i-1]) * b[i];}ans += (r-b[ed-1]) * b[ed];}else ans += (r-l+1) * b[st];cout << ans << endl;return 0 ; }法2:分塊:(還未看)
#include<bits/stdc++.h> #define IO ios::sync_with_stdio(false);\cin.tie(0);\cout.tie(0);using namespace std; typedef long long ll; const int maxn = 1e5+10;ll last(ll x) {int len = int(log10(x)) + 1; //數(shù)字位數(shù)ll ans = 0,cnt = 0;for(int i=0; i<len; i++) //同等位數(shù)最大最小幸運(yùn)數(shù)ans = ans*10+4,cnt = cnt*10+7;if(x>cnt) //位數(shù)+1return ans*10+4;while(ans<x) {ll res = cnt;for(int i=0; i<1<<len; i++) {ll tmp = 0;for(int j=0; j<len; j++) {if(i&(1<<j))tmp = tmp*10+7;elsetmp = tmp*10+4;}if(tmp>=x)res = min(res,tmp);}ans = res;}return ans; }int main() {ll l,r;cin>>l>>r;ll now = l,ans = 0;while(true) {ll la = last(now);if(la>r) {ans+= la * (r-now+1);break;} elseans += la * (la-now+1);now = la+1;}cout<<ans<<endl;return 0; }?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的*【CodeForces - 122C 】Lucky Sum (bfs记录状态,二分查找,有坑)(或分块)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nbj.exe - nbj是什么进程 有
- 下一篇: 【HDU - 2030 】汉字统计 (C