Editorial for Đếm Số Trong Đoạn


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

\(\color{#ff0000}{\text{Spoiler Alert}_{{}_{{}^{{}^{v2.5}}}}}\)

\(\color{#ff0000}{\text{Khuyến khích bạn đọc trước khi đọc phần lời giải xin hãy thử code ra thuật của mình dù nó có sai hay đúng}}\)

\(\color{#ff0000}{\text{Sau đó từ phần bài giải và thuật toán trước đó mà đối chiếu, rút nhận xét với thuật của mình và thu được bài học (không lãng phí thời gian đâu).}}\)

\(\color{#ff0000}{\text{Mình xin rút kinh nghiệm và chấn chỉnh bản thân nếu trong editorial có gì sai sót, và bạn có thể gửi feedback }}\) ở đây



\(\color{#300000}{\text{Hint 1 <Duyệt trâu>}}\)

Với mỗi truy vấn ta duyệt từ l tới r để kiểm tra.

Độ phức tạp thời gian tổng thể của cách này sẽ là \(O(q * (r-l+1))\)


\(\color{#300000}{\text{Hint 2 <Quy hoạch động>}}\)

Bài này sẽ dùng quy hoạch động chữ số và đệ quy có nhớ, để hiểu cách làm thì các bạn có thể đọc code dưới đây.

Độ phức tạp thời gian tổng thể của cách này sẽ xấp xỉ \(2 * 10^7\) ( kích thước mảng dp )


C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll>ii;
const ll mod=1e9+7;
ii dp[20][5433][181];
ll kq,l,r,coso[20];
vector<int>dg;
int q,k,P[11];
bool lcm[5433][181];

ii get(int pos,int sum1,int sum2,bool dabe)
{
    // first là tổng còn second là số lượng
    if(pos==-1&&(lcm[sum1][sum2]))return ii{0,1};else
        if(pos==-1)return ii{0,0};
    if(dp[pos][sum1][sum2]!=ii{-1,0}&&dabe)return dp[pos][sum1][sum2];
    ii res={0,0};
    for(int i=0;i<=max(dg[pos],dabe*9);i++)
    {
        ii cc=get(pos-1,sum1+P[i],sum2+i,dabe|(i<dg[pos]));
        res.first=((res.first+cc.first)%mod+((i*coso[pos])%mod*(cc.second%mod))%mod)%mod;
        res.second+=cc.second;
    }
    if(dabe)dp[pos][sum1][sum2]=res;
    return res;
}

ll call(ll x)
{
    if(x==0)return 0;
    dg.clear();
    for(;x>0;x/=10)dg.push_back(x%10);
    return get(dg.size()-1,0,0,0).first;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
    coso[0]=1;
    P[0]=0;
    for(int i=1;i<=9;i++)P[i]=i*i+P[i-1];
    for(int i=1;i<=18;i++)coso[i]=coso[i-1]*10%mod;
    for(int i=0;i<=5432;i++)for(int j=0;j<=180;j++)
        if(__gcd(i,j)==1)lcm[i][j]=1;
            else lcm[i][j]=0;
    for(int i=0;i<=19;i++)for(int j=0;j<=5432;j++)for(int k=0;k<=180;k++)dp[i][j][k]={-1,0};
    cin>>q;
    for(int i=1;i<=q;i++)
    {
        cin>>l>>r;
        cout<<(call(r)-call(l-1)+mod*mod)%mod<<"\n";
    }
    return 0;
}


Comments

There are no comments at the moment.