CSES - Shared codeLink to this code: https://cses.fi/paste/716421c81ec746975af8b3/
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
// #pragma GCC optimize "trapv"
#pragma GCC optimize("O3")
#pragma GCC target("avx,avx2,sse,sse2,sse3,sse4,popcnt,fma") 
#pragma GCC optimize("unroll-loops")
#define ll long long
 
int const siz = 2e5;
ll arr[siz], curr_ans;
 
int64_t peanoOrder(int x,int y,int m) {
    vector<vector<int>> a(2, vector<int>(m));
    int sum0 = 0, sum1 = 0;
    int ptr = m-1;
    while (x) {
        a[0][ptr] = x%3;
        sum0 += a[0][ptr];
        ptr--;
        x /= 3;
    }
    ptr = m-1;
    while (y) {
        a[1][ptr] = y%3;
        sum1 += a[1][ptr];
        ptr--;
        y /= 3;
    }

    for (int i = m-1; i >= 0; i--) {
        sum1 -= a[1][i];
        if (sum0&1)
            a[1][i] = 2 - a[1][i];
        sum0 -= a[0][i];
        if (sum1&1)
            a[0][i] = 2 - a[0][i];
    }

    int64_t num = 0, base = 1;
    for (int j = m-1; j >= 0; j--) {
        num += base * a[1][j];
        base *= 3;
        num += base * a[0][j];
        base *= 3;
    }
    return num;
}
 
struct query {
    int L,R,idx;
    ll ord;
 
    query() {}
    query(int L_,int R_,int idx_) {
        L = L_, R = R_;
        ord = peanoOrder(L, R, 13);
        idx = idx_;
    }
};
 
inline bool operator<(const query &a, const query &b) {
    return a.ord < b.ord;
}
 
inline void add(int x) {
    curr_ans += arr[x];
}
 
inline void remove(int x) {
    curr_ans -= arr[x];
}
 
void solve() {
    /// -------------- input ------------- 
    int n,q; cin >> n >> q;
    for (int i = 0; i < n; i++) 
        cin >> arr[i];
    vector<pair<int,int>> query_list(q);
    vector<ll> ans(q);
    for (auto& i: query_list) {
        cin >> i.first >> i.second;
        i.first--, i.second--;
    }
    
    /// -------------- query construction -------------
    vector<query> Q(q);
    for (int i = 0; i < q; i++)
        Q[i] = query(query_list[i].first, query_list[i].second, i);
 
    /// -------------- SORT QUERIES -------------
    sort(Q.begin(), Q.end());
 
    // --------------- Sliding window ------------
    int l = 0, r = -1;
    for (auto i: Q) {
        while (r<i.R) {
            r++;
            add(r);
        }
        while (l>i.L) {
            l--;
            add(l);
        }
        while (r>i.R) {
            remove(r);
            r--;
        }
        while (l<i.L) {
            remove(l);
            l++;
        }
        ans[i.idx] = curr_ans;
    }
 
    // ----------------- output -------------------
    for (ll i: ans)
        cout << i << "\n";
}
 
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    solve();
    return 0;
}