幸運數字Ⅱ(打表+思路)

題目鏈接:幸運數字Ⅱ

思路:
打表你會發現1e9以內的數,有1022個幸運數,將他們存入數組即可。
然後查找每一個數的next(l)的值(我們這裏是按幸運數來計算的,不需要遍歷所有的數)。

打印幸運數的思路:因爲只有4和7,所以先記錄4,和7,並放入隊列中,從隊列中取一個數,將它分別乘以4和7,小於1e9的記錄並放入隊列中,直到隊列爲空爲止,最後要加入4444444444,因爲例如1e9的next值爲4444444444(upper_bound()會查找到),從小到大排序即可。(因爲next的特性,所以只能用upper_bound())

下面是代碼:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e4+9;
ll cun[maxn];

int doo()//打表記錄每一個幸運數
{
    queue<ll>q;
    cun[0]=(ll)4;
    cun[1]=(ll)7;
    while(!q.empty())q.pop();
    int len=2;
    q.push(cun[0]);
    q.push(cun[1]);
    while(!q.empty())
    {
        ll x=q.front();
        q.pop();
        if(x*10+4<1e9)
        {
            cun[len++]=x*10+4;
            q.push(x*10+4);
        }
        if(x*10+7<1e9)
        {
            cun[len++]=x*10+7;
            q.push(x*10+7);
        }
    }
    return len;
}
int main()
{
    ll a,b;
    int len=doo();
    cun[len++]=4444444444;
    sort(cun,cun+len);//從小到大排序
    while(~scanf("%lld%lld",&a,&b))
    {
        int i=upper_bound(cun,cun+len,a)-cun;//查找離a,最近的幸運值
        if(cun[i-1]==a)//有可能a就是一個幸運值,所以i--;
            i--;
        ll sum;

        if(cun[i]<=b)//判斷[a,b]中有沒有幸運值
            sum=(cun[i]-a+1)*cun[i];
        else
        {
            sum=(b-a+1)*cun[i];
            printf("%lld\n",sum);
            continue;
        }

        for(i++; cun[i]<=b; i++)//通過幸運值跳着查找。
            sum+=(cun[i]-cun[i-1])*cun[i];

        if(cun[i]>b&&cun[i-1]!=b)//如果b不是一個幸運值
            sum+=(b-cun[i-1])*cun[i];
        printf("%lld\n",sum);
    }
    return 0;
}
發佈了186 篇原創文章 · 獲贊 14 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章