Source Code
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int mod=1e9+7;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    string s;
    cin>>s;
    string x=s;
    reverse(x.begin(),x.end());
    ll n=s.size();
    vector<vector<ll>>pre(n,vector<ll>(4,0));
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<=3; j++)
        {
            if(i)pre[i][j]=pre[i-1][j];
        }
        pre[i][i%4]+=(x[i]=='1');
    }
    int t;
    cin>>t;
    while(t--)
    {
        int l,r;
        ll sum=0;
        cin>>l>>r;
        l--,r--;
        if(r-l+1<=10)
        {
            for(int i=r,y=1; i>=l; i--)
            {
                sum+=(s[i]=='1')*y;
                y*=2;
            }
            cout<<sum%10<<endl;
        }
        else
        {
            r=n-r-1,l=n-l-1;
            swap(l,r);
            vector<ll>a(4,0),b{2,4,8,6};
            for(int j=0; j<4; j++)
            {
                if(!l)a[j]=pre[r][(l+j+1)%4];
                else a[j]=pre[r][(l+j+1)%4]-pre[l-1][(l+j+1)%4];
            }
            a[3]-=(x[l]=='1');
            for(int i=0;i<4;i++){
                sum+=b[i]*a[i];
            }
            sum+=(x[l]=='1');
            sum%=10;
            cout<<sum<<endl;
        }
    }
    return 0;
}
Copy
Binarithm Amrharb
GNU G++17
817 ms
15.2 MB
Accepted