#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");

vector<vector<long long int> > query;
struct SumSegmentTree {
    private:
    vector<long long int> v; // vettore che contiene l'albero
    vector<long long int> u; // vettore di update
    long long int n; //numero nodi long long interni
    const long long int NULL_VALUE = 0; //zero dell'operazione
    public:
    SumSegmentTree(long long int num) {
        v.resize((1 << (long long int)(ceil(log2(num))+1))-1, NULL_VALUE);//completo bilanciato
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
    }

    SumSegmentTree(vector<long long int> &source) {
        v.resize((1 << (long long int)(ceil(log2(source.size()))+1))-1, NULL_VALUE);//completo bilanciatoų
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
        for (long long int i = 0; i < source.size(); i++) {
            v[i + n] = source[i];
        }
        for (long long int i = n - 1; i >= 0; i--) {
            updateNode(i);
        }
    }
    private:
    long long int left(long long int i) {
        return i*2+1;
    }

    long long int right(long long int i) {
        return i*2+2;
    }

    long long int parent(long long int i) {
        return (i - 1) / 2;
    }

    long long int mergeValues(long long int v1, long long int v2) {
        return v1 + v2;
    }

    void updateNode(long long int i) {
        v[i] = mergeValues(v[left(i)], v[right(i)]);
    }

    void lazyUpdate(long long int i) {
        if (u[i] != 0) {
            v[i] += u[i];
            if (i < v.size() / 2) {
                u[left(i)] += u[i] / 2;
                u[right(i)] += u[i] / 2;
            }
            u[i] = 0;
        }
    }

    long long int rangeQuery(long long int i, long long int l, long long int r, long long int a, long long int b) {
        lazyUpdate(i); //Aggiornamento in lettura

        if (l >= a && r <= b) {
            return v[i];
        }
        if (r < a || l > b) {
            return NULL_VALUE;
        }
        long long int m = (l + r) / 2;
        return mergeValues(rangeQuery(left(i), l, m, a, b), rangeQuery(right(i), m + 1, r, a, b));
    }

    void updateToRoot(long long int i) {
        updateNode(i);
        if (i != 0) {
            updateToRoot(parent(i));
        }
    }

    void rangeAdd(long long int i, long long int a, long long int b, long long int l, long long int r, long long int off) {
        lazyUpdate(i);

        if (l >= a && r <= b) {
            u[i] += off * (r - l + 1);
            lazyUpdate(i);

        } else if (!(r < a || l > b)) { //overlap parziale
            long long int m = (l + r) / 2;
            rangeAdd(left(i), a, b, l , m, off);
            rangeAdd(right(i), a, b, m + 1, r, off);
            updateNode(i);
        }
    }

    public:

    long long int rangeSum(long long int a, long long int b) {
        return rangeQuery(0, 0, n, a, b);
    }

    void update(long long int index, long long int value) {
        long long int i = n + index;
        v[i] = value;
        updateToRoot(parent(i));
    }

    void rangeUpdate(long long int a, long long int b, long long int offset) {
        rangeAdd(0, a, b, 0, n, offset);
    }

    vector<long long int> get_v(){
        for(long long int  i = 0; i < v.size(); i++){
            lazyUpdate(i);
        }
        long long int t = 0;
        vector<long long int> tmp;
        for(int i = v.size()/2; i < v.size(); i++){
            if(v[i] != 0){
                t++;
                tmp.push_back(v[i]);
            }
        }
        sort(tmp.rbegin(),tmp.rend());
        return tmp;
    }

    void print() {
        long long int i = 0;
        long long int livNum = 1;
        while (i < v.size()) {
            for (long long int j = 0; j < livNum; j++) {
                cout << v[i] << "(" << u[i] << ")" << " "<<"n: "<<i<<" ";
                i++;
            }
            livNum *= 2;
            cout << "\n";
        }
    }
};

int main(){
    long long int n, q, a, b;
    cin>>n>>q;
    vector<long long int> v;
    for(long long int i = 0; i < n; i++){
        cin>>a;
        v.push_back(a);
    }
    vector<long long int> p(n+5);
    SumSegmentTree st(p);
    for(long long int i = 0; i < q; i++){
        cin>>a>>b;
        vector<long long int> t;
        st.rangeUpdate(a,b,1);
        t.push_back(a), t.push_back(b);

    }

    long long int sum = 0;
    sort(v.rbegin(), v.rend());
    vector<long long int> o = st.get_v();

    for(long long int i = 0; i < o.size(); i++){
        sum += v[i]*o[i];
    }
    cout<<sum;

}


#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");

vector<vector<int> > query;
struct SumSegmentTree {
    private:
    vector<int> v; // vettore che contiene l'albero
    vector<int> u; // vettore di update
    int n; //numero nodi interni
    const int NULL_VALUE = 0; //zero dell'operazione
    public:
    SumSegmentTree(int num) {
        v.resize((1 << (int)(ceil(log2(num))+1))-1, NULL_VALUE);//completo bilanciato
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
    }

    SumSegmentTree(vector<int> &source) {
        v.resize((1 << (int)(ceil(log2(source.size()))+1))-1, NULL_VALUE);//completo bilanciatoų
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
        for (int i = 0; i < source.size(); i++) {
            v[i + n] = source[i];
        }
        for (int i = n - 1; i >= 0; i--) {
            updateNode(i);
        }
    }
    private:
    int left(int i) {
        return i*2+1;
    }

    int right(int i) {
        return i*2+2;
    }

    int parent(int i) {
        return (i - 1) / 2;
    }

    int mergeValues(int v1, int v2) {
        return v1 + v2;
    }

    void updateNode(int i) {
        v[i] = mergeValues(v[left(i)], v[right(i)]);
    }

    void lazyUpdate(int i) {
        if (u[i] != 0) {
            v[i] += u[i];
            if (i < v.size() / 2) {
                u[left(i)] += u[i] / 2;
                u[right(i)] += u[i] / 2;
            }
            u[i] = 0;
        }
    }

    int rangeQuery(int i, int l, int r, int a, int b) {
        lazyUpdate(i); //Aggiornamento in lettura

        if (l >= a && r <= b) {
            return v[i];
        }
        if (r < a || l > b) {
            return NULL_VALUE;
        }
        int m = (l + r) / 2;
        return mergeValues(rangeQuery(left(i), l, m, a, b), rangeQuery(right(i), m + 1, r, a, b));
    }

    void updateToRoot(int i) {
        updateNode(i);
        if (i != 0) {
            updateToRoot(parent(i));
        }
    }

    void rangeAdd(int i, int a, int b, int l, int r, int off) {
        lazyUpdate(i);

        if (l >= a && r <= b) {
            u[i] += off * (r - l + 1);
            lazyUpdate(i);

        } else if (!(r < a || l > b)) { //overlap parziale
            int m = (l + r) / 2;
            rangeAdd(left(i), a, b, l , m, off);
            rangeAdd(right(i), a, b, m + 1, r, off);
            updateNode(i);
        }
    }

    public:

    int rangeSum(int a, int b) {
        return rangeQuery(0, 0, n, a, b);
    }

    void update(int index, int value) {
        int i = n + index;
        v[i] = value;
        updateToRoot(parent(i));
    }

    void rangeUpdate(int a, int b, int offset) {
        rangeAdd(0, a, b, 0, n, offset);
    }

    vector<int> get_v(int t){
        for(unsigned long long int  i = 0; i < v.size(); i++){
            lazyUpdate(i);
        }
        vector<int> tmp;
        for(int i = 0; i < t; i++){
            tmp.push_back(v[v.size()/2+i+1]);
        }
        return tmp;
    }

    void print() {
        int i = 0;
        int livNum = 1;
        while (i < v.size()) {
            for (int j = 0; j < livNum; j++) {
                cout << v[i] << "(" << u[i] << ")" << " "<<"n: "<<i<<" ";
                i++;
            }
            livNum *= 2;
            cout << "\n";
        }
    }
};

int main(){
    int n, q, a, b;
    cin>>n>>q;
    vector<int> v;
    for(int i = 0; i < n; i++){
        cin>>a;
        v.push_back(a);
    }
    vector<int> p(n+5);
    for(int i = 0; i < q; i++){
        cin>>a>>b;
        p[a]++;
        p[b+1]--;
    }

    for(int i = 1; i < n+2;i++){
        p[i] = p[i]+p[i-1];
    }

    sort(p.rbegin(),p.rend());
    long long int sum = 0;
    sort(v.rbegin(), v.rend());
    for(int i = 0; p[i] != 0; i++){
        sum += v[i]*p[i];
    }
    cout<<sum;

}


#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");

vector<vector<int> > query;
struct SumSegmentTree {
    private:
    vector<int> v; // vettore che contiene l'albero
    vector<int> u; // vettore di update
    int n; //numero nodi interni
    const int NULL_VALUE = 0; //zero dell'operazione
    public:
    SumSegmentTree(int num) {
        v.resize((1 << (int)(ceil(log2(num))+1))-1, NULL_VALUE);//completo bilanciato
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
    }

    SumSegmentTree(vector<int> &source) {
        v.resize((1 << (int)(ceil(log2(source.size()))+1))-1, NULL_VALUE);//completo bilanciatoų
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
        for (int i = 0; i < source.size(); i++) {
            v[i + n] = source[i];
        }
        for (int i = n - 1; i >= 0; i--) {
            updateNode(i);
        }
    }
    private:
    int left(int i) {
        return i*2+1;
    }

    int right(int i) {
        return i*2+2;
    }

    int parent(int i) {
        return (i - 1) / 2;
    }

    int mergeValues(int v1, int v2) {
        return v1 + v2;
    }

    void updateNode(int i) {
        v[i] = mergeValues(v[left(i)], v[right(i)]);
    }

    void lazyUpdate(int i) {
        if (u[i] != 0) {
            v[i] += u[i];
            if (i < v.size() / 2) {
                u[left(i)] += u[i] / 2;
                u[right(i)] += u[i] / 2;
            }
            u[i] = 0;
        }
    }

    int rangeQuery(int i, int l, int r, int a, int b) {
        lazyUpdate(i); //Aggiornamento in lettura

        if (l >= a && r <= b) {
            return v[i];
        }
        if (r < a || l > b) {
            return NULL_VALUE;
        }
        int m = (l + r) / 2;
        return mergeValues(rangeQuery(left(i), l, m, a, b), rangeQuery(right(i), m + 1, r, a, b));
    }

    void updateToRoot(int i) {
        updateNode(i);
        if (i != 0) {
            updateToRoot(parent(i));
        }
    }

    void rangeAdd(int i, int a, int b, int l, int r, int off) {
        lazyUpdate(i);

        if (l >= a && r <= b) {
            u[i] += off * (r - l + 1);
            lazyUpdate(i);

        } else if (!(r < a || l > b)) { //overlap parziale
            int m = (l + r) / 2;
            rangeAdd(left(i), a, b, l , m, off);
            rangeAdd(right(i), a, b, m + 1, r, off);
            updateNode(i);
        }
    }

    public:

    int rangeSum(int a, int b) {
        return rangeQuery(0, 0, n, a, b);
    }

    void update(int index, int value) {
        int i = n + index;
        v[i] = value;
        updateToRoot(parent(i));
    }

    void rangeUpdate(int a, int b, int offset) {
        rangeAdd(0, a, b, 0, n, offset);
    }

    vector<int> get_v(int t){
        for(unsigned long long int  i = 0; i < v.size(); i++){
            lazyUpdate(i);
        }
        vector<int> tmp;
        for(int i = 0; i < t; i++){
            tmp.push_back(v[v.size()/2+i+1]);
        }
        return tmp;
    }

    void print() {
        int i = 0;
        int livNum = 1;
        while (i < v.size()) {
            for (int j = 0; j < livNum; j++) {
                cout << v[i] << "(" << u[i] << ")" << " "<<"n: "<<i<<" ";
                i++;
            }
            livNum *= 2;
            cout << "\n";
        }
    }
};

int main(){
    int n, q, a, b;
    cin>>n>>q;
    vector<int> v;
    for(int i = 0; i < n; i++){
        cin>>a;
        v.push_back(a);
    }
    vector<int> p(n+5);
    SumSegmentTree st(p);
    for(int i = 0; i < q; i++){
        cin>>a>>b;
        vector<int> t;
        st.rangeUpdate(a,b,1);
        t.push_back(a), t.push_back(b);
        query.push_back(t);
    }
    sort(query.begin(),query.end());
    int top = 0;
    int start, end;
    start = query[0][0];
    end = query[0][1];
    for(int i = 1; i < query.size(); i++){
        if(query[i][0] <= end){
            end = max(end,query[i][1]);
        }else{
            top += end -start +1;
            start = query[i][0];
            end = query[i][1];

        }
    }
    top += end -start +1;

    int sum = 0;
    sort(v.rbegin(), v.rend());
    vector<int> o = st.get_v(top);
    sort(o.rbegin(), o.rend());

    for(int i = 0; i < top; i++){
        sum += v[i]*o[i];
    }
    cout<<sum;

}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;

signed main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
    int n, q;
    cin>>n>>q;
    vector<int> v(n);
    for(int &i : v)
        cin>>i;
    sort(v.rbegin(), v.rend());
    vector<int> e(n+10);
    for(int i = 0;  i < q; i++){
        int a, b;
        cin>>a>>b;
        a--;b--;
        e[a]++;
        e[b+1]--;
    }
    priority_queue<ll> qq;
    qq.push(e[0]);
    for(int i = 1; i < n; i++){
        e[i] = e[i] + e[i-1];
        qq.push(e[i]);
    }
    ll sol = 0;
    int i = 0;
    while(!qq.empty()){
        ll c = qq.top();qq.pop();
        sol += c * v[i++];
    }
    cout << sol;
}


#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");

vector<vector<long long int> > query;
struct SumSegmentTree {
    private:
    vector<long long int> v; // vettore che contiene l'albero
    vector<long long int> u; // vettore di update
    long long int n; //numero nodi long long interni
    const long long int NULL_VALUE = 0; //zero dell'operazione
    public:
    SumSegmentTree(long long int num) {
        v.resize((1 << (long long int)(ceil(log2(num))+1))-1, NULL_VALUE);//completo bilanciato
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
    }

    SumSegmentTree(vector<long long int> &source) {
        v.resize((1 << (long long int)(ceil(log2(source.size()))+1))-1, NULL_VALUE);//completo bilanciatoų
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
        for (long long int i = 0; i < source.size(); i++) {
            v[i + n] = source[i];
        }
        for (long long int i = n - 1; i >= 0; i--) {
            updateNode(i);
        }
    }
    private:
    long long int left(long long int i) {
        return i*2+1;
    }

    long long int right(long long int i) {
        return i*2+2;
    }

    long long int parent(long long int i) {
        return (i - 1) / 2;
    }

    long long int mergeValues(long long int v1, long long int v2) {
        return v1 + v2;
    }

    void updateNode(long long int i) {
        v[i] = mergeValues(v[left(i)], v[right(i)]);
    }

    void lazyUpdate(long long int i) {
        if (u[i] != 0) {
            v[i] += u[i];
            if (i < v.size() / 2) {
                u[left(i)] += u[i] / 2;
                u[right(i)] += u[i] / 2;
            }
            u[i] = 0;
        }
    }

    long long int rangeQuery(long long int i, long long int l, long long int r, long long int a, long long int b) {
        lazyUpdate(i); //Aggiornamento in lettura

        if (l >= a && r <= b) {
            return v[i];
        }
        if (r < a || l > b) {
            return NULL_VALUE;
        }
        long long int m = (l + r) / 2;
        return mergeValues(rangeQuery(left(i), l, m, a, b), rangeQuery(right(i), m + 1, r, a, b));
    }

    void updateToRoot(long long int i) {
        updateNode(i);
        if (i != 0) {
            updateToRoot(parent(i));
        }
    }

    void rangeAdd(long long int i, long long int a, long long int b, long long int l, long long int r, long long int off) {
        lazyUpdate(i);

        if (l >= a && r <= b) {
            u[i] += off * (r - l + 1);
            lazyUpdate(i);

        } else if (!(r < a || l > b)) { //overlap parziale
            long long int m = (l + r) / 2;
            rangeAdd(left(i), a, b, l , m, off);
            rangeAdd(right(i), a, b, m + 1, r, off);
            updateNode(i);
        }
    }

    public:

    long long int rangeSum(long long int a, long long int b) {
        return rangeQuery(0, 0, n, a, b);
    }

    void update(long long int index, long long int value) {
        long long int i = n + index;
        v[i] = value;
        updateToRoot(parent(i));
    }

    void rangeUpdate(long long int a, long long int b, long long int offset) {
        rangeAdd(0, a, b, 0, n, offset);
    }

    vector<long long int> get_v(){
        for(long long int  i = 0; i < v.size(); i++){
            lazyUpdate(i);
        }
        vector<long long int> tmp;
        for(int i = v.size()/2; i < v.size(); i++){
            if(v[i] != 0){
                tmp.push_back(v[i]);
            }
        }
        sort(tmp.rbegin(),tmp.rend());
        return tmp;
    }

    void print() {
        long long int i = 0;
        long long int livNum = 1;
        while (i < v.size()) {
            for (long long int j = 0; j < livNum; j++) {
                cout << v[i] << "(" << u[i] << ")" << " "<<"n: "<<i<<" ";
                i++;
            }
            livNum *= 2;
            cout << "\n";
        }
    }
};

int main(){
    long long int n, q, a, b;
    cin>>n>>q;
    vector<long long int> v;
    for(long long int i = 0; i < n; i++){
        cin>>a;
        v.push_back(a);
    }
    vector<long long int> p(n+5);
    SumSegmentTree st(p);
    for(long long int i = 0; i < q; i++){
        cin>>a>>b;
        st.rangeUpdate(a,b,1);
    }

    long long int sum = 0;
    sort(v.rbegin(), v.rend());
    vector<long long int> o = st.get_v();

    for(long long int i = 0; i < o.size(); i++){
        sum += v[i]*o[i];
    }
    cout<<sum;

}


#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");

vector<vector<int> > query;
struct SumSegmentTree {
    private:
    vector<int> v; // vettore che contiene l'albero
    vector<int> u; // vettore di update
    int n; //numero nodi interni
    const int NULL_VALUE = 0; //zero dell'operazione
    public:
    SumSegmentTree(int num) {
        v.resize((1 << (int)(ceil(log2(num))+1))-1, NULL_VALUE);//completo bilanciato
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
    }

    SumSegmentTree(vector<int> &source) {
        v.resize((1 << (int)(ceil(log2(source.size()))+1))-1, NULL_VALUE);//completo bilanciatoų
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
        for (int i = 0; i < source.size(); i++) {
            v[i + n] = source[i];
        }
        for (int i = n - 1; i >= 0; i--) {
            updateNode(i);
        }
    }
    private:
    int left(int i) {
        return i*2+1;
    }

    int right(int i) {
        return i*2+2;
    }

    int parent(int i) {
        return (i - 1) / 2;
    }

    int mergeValues(int v1, int v2) {
        return v1 + v2;
    }

    void updateNode(int i) {
        v[i] = mergeValues(v[left(i)], v[right(i)]);
    }

    void lazyUpdate(int i) {
        if (u[i] != 0) {
            v[i] += u[i];
            if (i < v.size() / 2) {
                u[left(i)] += u[i] / 2;
                u[right(i)] += u[i] / 2;
            }
            u[i] = 0;
        }
    }

    int rangeQuery(int i, int l, int r, int a, int b) {
        lazyUpdate(i); //Aggiornamento in lettura

        if (l >= a && r <= b) {
            return v[i];
        }
        if (r < a || l > b) {
            return NULL_VALUE;
        }
        int m = (l + r) / 2;
        return mergeValues(rangeQuery(left(i), l, m, a, b), rangeQuery(right(i), m + 1, r, a, b));
    }

    void updateToRoot(int i) {
        updateNode(i);
        if (i != 0) {
            updateToRoot(parent(i));
        }
    }

    void rangeAdd(int i, int a, int b, int l, int r, int off) {
        lazyUpdate(i);

        if (l >= a && r <= b) {
            u[i] += off * (r - l + 1);
            lazyUpdate(i);

        } else if (!(r < a || l > b)) { //overlap parziale
            int m = (l + r) / 2;
            rangeAdd(left(i), a, b, l , m, off);
            rangeAdd(right(i), a, b, m + 1, r, off);
            updateNode(i);
        }
    }

    public:

    int rangeSum(int a, int b) {
        return rangeQuery(0, 0, n, a, b);
    }

    void update(int index, int value) {
        int i = n + index;
        v[i] = value;
        updateToRoot(parent(i));
    }

    void rangeUpdate(int a, int b, int offset) {
        rangeAdd(0, a, b, 0, n, offset);
    }

    vector<int> get_v(int t){
        for(unsigned long long int  i = 0; i < v.size(); i++){
            lazyUpdate(i);
        }
        vector<int> tmp;
        for(int i = 0; i < t; i++){
            tmp.push_back(v[v.size()/2+i+1]);
        }
        return tmp;
    }

    void print() {
        int i = 0;
        int livNum = 1;
        while (i < v.size()) {
            for (int j = 0; j < livNum; j++) {
                cout << v[i] << "(" << u[i] << ")" << " "<<"n: "<<i<<" ";
                i++;
            }
            livNum *= 2;
            cout << "\n";
        }
    }
};

int main(){
    int n, q, a, b;
    cin>>n>>q;
    vector<long long int> v;
    for(int i = 0; i < n; i++){
        cin>>a;
        v.push_back(a);
    }
    vector<long long int> p(n+5);
    for(int i = 0; i < q; i++){
        cin>>a>>b;
        p[a]++;
        p[b+1]--;
    }

    for(int i = 1; i < n+2;i++){
        p[i] = p[i]+p[i-1];
    }

    sort(p.rbegin(),p.rend());
    long long int sum = 0;
    sort(v.rbegin(), v.rend());
    for(int i = 0; p[i] != 0; i++){
        sum += v[i]*p[i];
    }
    cout<<sum;

}


#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");

vector<vector<int> > query;
struct SumSegmentTree {
    private:
    vector<int> v; // vettore che contiene l'albero
    vector<int> u; // vettore di update
    int n; //numero nodi interni
    const int NULL_VALUE = 0; //zero dell'operazione
    public:
    SumSegmentTree(int num) {
        v.resize((1 << (int)(ceil(log2(num))+1))-1, NULL_VALUE);//completo bilanciato
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
    }

    SumSegmentTree(vector<int> &source) {
        v.resize((1 << (int)(ceil(log2(source.size()))+1))-1, NULL_VALUE);//completo bilanciatoų
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
        for (int i = 0; i < source.size(); i++) {
            v[i + n] = source[i];
        }
        for (int i = n - 1; i >= 0; i--) {
            updateNode(i);
        }
    }
    private:
    int left(int i) {
        return i*2+1;
    }

    int right(int i) {
        return i*2+2;
    }

    int parent(int i) {
        return (i - 1) / 2;
    }

    int mergeValues(int v1, int v2) {
        return v1 + v2;
    }

    void updateNode(int i) {
        v[i] = mergeValues(v[left(i)], v[right(i)]);
    }

    void lazyUpdate(int i) {
        if (u[i] != 0) {
            v[i] += u[i];
            if (i < v.size() / 2) {
                u[left(i)] += u[i] / 2;
                u[right(i)] += u[i] / 2;
            }
            u[i] = 0;
        }
    }

    int rangeQuery(int i, int l, int r, int a, int b) {
        lazyUpdate(i); //Aggiornamento in lettura

        if (l >= a && r <= b) {
            return v[i];
        }
        if (r < a || l > b) {
            return NULL_VALUE;
        }
        int m = (l + r) / 2;
        return mergeValues(rangeQuery(left(i), l, m, a, b), rangeQuery(right(i), m + 1, r, a, b));
    }

    void updateToRoot(int i) {
        updateNode(i);
        if (i != 0) {
            updateToRoot(parent(i));
        }
    }

    void rangeAdd(int i, int a, int b, int l, int r, int off) {
        lazyUpdate(i);

        if (l >= a && r <= b) {
            u[i] += off * (r - l + 1);
            lazyUpdate(i);

        } else if (!(r < a || l > b)) { //overlap parziale
            int m = (l + r) / 2;
            rangeAdd(left(i), a, b, l , m, off);
            rangeAdd(right(i), a, b, m + 1, r, off);
            updateNode(i);
        }
    }

    public:

    int rangeSum(int a, int b) {
        return rangeQuery(0, 0, n, a, b);
    }

    void update(int index, int value) {
        int i = n + index;
        v[i] = value;
        updateToRoot(parent(i));
    }

    void rangeUpdate(int a, int b, int offset) {
        rangeAdd(0, a, b, 0, n, offset);
    }

    vector<int> get_v(int t){
        for(unsigned long long int  i = 0; i < v.size(); i++){
            lazyUpdate(i);
        }
        vector<int> tmp;
        for(int i = 0; i < t; i++){
            tmp.push_back(v[v.size()/2+i+1]);
        }
        return tmp;
    }

    void print() {
        int i = 0;
        int livNum = 1;
        while (i < v.size()) {
            for (int j = 0; j < livNum; j++) {
                cout << v[i] << "(" << u[i] << ")" << " "<<"n: "<<i<<" ";
                i++;
            }
            livNum *= 2;
            cout << "\n";
        }
    }
};

int main(){
    int n, q, a, b;
    cin>>n>>q;
    vector<int> v;
    for(int i = 0; i < n; i++){
        cin>>a;
        v.push_back(a);
    }
    vector<int> p(n+5);
    SumSegmentTree st(p);
    for(int i = 0; i < q; i++){
        cin>>a>>b;
        vector<int> t;
        st.rangeUpdate(a,b,1);
        t.push_back(a), t.push_back(b);
        query.push_back(t);
    }
    sort(query.begin(),query.end());
    int top = 0;
    int start, end;
    start = query[0][0];
    end = query[0][1];
    for(int i = 1; i < query.size(); i++){
        if(query[i][0] <= end){
            end = max(end,query[i][1]);
        }else{
            top += end -start +1;
            start = query[i][0];
            end = query[i][1];

        }
    }
    top += end -start +1;

    long long int sum = 0;
    sort(v.rbegin(), v.rend());
    vector<int> o = st.get_v(top);
    sort(o.rbegin(), o.rend());

    for(int i = 0; i < top; i++){
        sum += v[i]*o[i];
    }
    cout<<sum;

}


#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");

vector<vector<long long int> > query;
struct SumSegmentTree {
    private:
    vector<long long int> v; // vettore che contiene l'albero
    vector<long long int> u; // vettore di update
    long long int n; //numero nodi long long interni
    const long long int NULL_VALUE = 0; //zero dell'operazione
    public:
    SumSegmentTree(long long int num) {
        v.resize((1 << (long long int)(ceil(log2(num))+1))-1, NULL_VALUE);//completo bilanciato
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
    }

    SumSegmentTree(vector<long long int> &source) {
        v.resize((1 << (long long int)(ceil(log2(source.size()))+1))-1, NULL_VALUE);//completo bilanciatoų
        u.resize(v.size(), NULL_VALUE);
        n = v.size() / 2;
        for (long long int i = 0; i < source.size(); i++) {
            v[i + n] = source[i];
        }
        for (long long int i = n - 1; i >= 0; i--) {
            updateNode(i);
        }
    }
    private:
    long long int left(long long int i) {
        return i*2+1;
    }

    long long int right(long long int i) {
        return i*2+2;
    }

    long long int parent(long long int i) {
        return (i - 1) / 2;
    }

    long long int mergeValues(long long int v1, long long int v2) {
        return v1 + v2;
    }

    void updateNode(long long int i) {
        v[i] = mergeValues(v[left(i)], v[right(i)]);
    }

    void lazyUpdate(long long int i) {
        if (u[i] != 0) {
            v[i] += u[i];
            if (i < v.size() / 2) {
                u[left(i)] += u[i] / 2;
                u[right(i)] += u[i] / 2;
            }
            u[i] = 0;
        }
    }

    long long int rangeQuery(long long int i, long long int l, long long int r, long long int a, long long int b) {
        lazyUpdate(i); //Aggiornamento in lettura

        if (l >= a && r <= b) {
            return v[i];
        }
        if (r < a || l > b) {
            return NULL_VALUE;
        }
        long long int m = (l + r) / 2;
        return mergeValues(rangeQuery(left(i), l, m, a, b), rangeQuery(right(i), m + 1, r, a, b));
    }

    void updateToRoot(long long int i) {
        updateNode(i);
        if (i != 0) {
            updateToRoot(parent(i));
        }
    }

    void rangeAdd(long long int i, long long int a, long long int b, long long int l, long long int r, long long int off) {
        lazyUpdate(i);

        if (l >= a && r <= b) {
            u[i] += off * (r - l + 1);
            lazyUpdate(i);

        } else if (!(r < a || l > b)) { //overlap parziale
            long long int m = (l + r) / 2;
            rangeAdd(left(i), a, b, l , m, off);
            rangeAdd(right(i), a, b, m + 1, r, off);
            updateNode(i);
        }
    }

    public:

    long long int rangeSum(long long int a, long long int b) {
        return rangeQuery(0, 0, n, a, b);
    }

    void update(long long int index, long long int value) {
        long long int i = n + index;
        v[i] = value;
        updateToRoot(parent(i));
    }

    void rangeUpdate(long long int a, long long int b, long long int offset) {
        rangeAdd(0, a, b, 0, n, offset);
    }

    vector<long long int> get_v(){
        for(long long int  i = 0; i < v.size(); i++){
            lazyUpdate(i);
        }
        long long int t = 0;
        for(int i = v.size()/2; i < v.size(); i++){
            if(v[i] != 0)
            t++;
        }
        vector<long long int> tmp;
        for(long long int i = 0; i < t; i++){
            tmp.push_back(v[v.size()/2+i+1]);
        }
        return tmp;
    }

    void print() {
        long long int i = 0;
        long long int livNum = 1;
        while (i < v.size()) {
            for (long long int j = 0; j < livNum; j++) {
                cout << v[i] << "(" << u[i] << ")" << " "<<"n: "<<i<<" ";
                i++;
            }
            livNum *= 2;
            cout << "\n";
        }
    }
};

int main(){
    long long int n, q, a, b;
    cin>>n>>q;
    vector<long long int> v;
    for(long long int i = 0; i < n; i++){
        cin>>a;
        v.push_back(a);
    }
    vector<long long int> p(n+5);
    SumSegmentTree st(p);
    for(long long int i = 0; i < q; i++){
        cin>>a>>b;
        vector<long long int> t;
        st.rangeUpdate(a,b,1);
        t.push_back(a), t.push_back(b);

    }

    long long int sum = 0;
    sort(v.rbegin(), v.rend());
    vector<long long int> o = st.get_v();
    sort(o.rbegin(), o.rend());

    for(long long int i = 0; i < o.size(); i++){
        sum += v[i]*o[i];
    }
    cout<<sum;

}


#include<bits/stdc++.h>
#define ll long long int
#define mod 1000000007
#define M INT_MAX;

using namespace std;
ll t[200010];
ll a[200010];
ll out;
int n,q,x,y,i;
int main()
{
    cin.tie(0);
    cin>>n>>q;
    for(i=0;i<n;i++) cin>>a[i];
    sort(a,a+n);
    for(i=0;i<q;i++)
    {
        cin>>x>>y;
        t[x-1]++;
        t[y]--;
    }
    for(i=1;i<n;i++)
        t[i]+=t[i-1];
    sort(t,t+n);
    for(i=0;i<n;i++)
    {
        out=out+t[i]*a[i];
    }
    cout<<out<<endl;

}


#include<bits/stdc++.h>
#define ll long long int
#define mod 1000000007
#define M INT_MAX;

using namespace std;
ll t[200010];
int main()
{
    cin.tie(0);
    int n,q,out=0;
    cin>>n>>q;
    ll a[n];
    for(ll i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    for(ll i=0;i<q;i++)
    {
        ll x,y;
        cin>>x>>y;
        t[x-1]++;
        t[y]--;
    }
    for(ll i=1;i<n;i++)
        t[i]+=t[i-1];
    sort(t,t+n);
    for(ll i=0;i<n;i++)
    {
        out=out+t[i]*a[i];
    }
    cout<<out;

return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define mod 1000000007
#define M 200000

using namespace std;
ll t[200010];
int main()
{
    int n,q,out=0;
    cin>>n>>q;
    ll a[n]={};
    for(ll i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    reverse(a,a+n);
    for(ll i=0;i<q;i++)
    {
        ll x,y;
        cin>>x>>y;
        for(ll j=x-1;j<y;j++)
        {
            t[j]++;
        }
    }
    sort(t,t+n);
    reverse(t,t+n);
    for(ll i=0;i<n;i++)
    {
        out=out+t[i]*a[i];
    }
    cout<<out;

return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define mod 1000000007

using namespace std;

int main()
{
    ll n,q,out=0;
    cin>>n>>q;
    ll a[n],l[q],r[q];
    ll ans[n+1]={};
    for(ll i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    reverse(a,a+n);
    for(ll i=0;i<q;i++)
    {
        cin>>l[i]>>r[i];
        for(ll j=l[i]-1;j<r[i];j++)
        {
            ans[j]++;
        }
    }
    sort(ans,ans+n);
    reverse(ans,ans+n);
    for(ll i=0;i<n;i++)
    {
        out=out+ans[i]*a[i];
    }
    cout<<out;

return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define mod 1000000007
#define M INT_MAX;

using namespace std;
ll t[200010];
ll a[200010];
ll out;

int main()
{
ll n,q,x,y,i;
    cin.tie(0);
    cin>>n>>q;
    for(i=0;i<n;i++) cin>>a[i];
    sort(a,a+n);
    for(i=0;i<q;i++)
    {
        cin>>x>>y;
        t[x-1]++;
        t[y]--;
    }
    for(i=1;i<n;i++)
        t[i]+=t[i-1];
    sort(t,t+n);
    for(i=0;i<n;i++)
    {
        out=out+t[i]*a[i];
    }
    cout<<out<<endl;

}


#include<bits/stdc++.h>
#define ll long long int
#define mod 1000000007
#define M 200000

using namespace std;
ll t[200010];
int main()
{
    int n,q,out=0;
    cin>>n>>q;
    ll a[n]={};
    for(ll i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    reverse(a,a+n);
    for(ll i=0;i<q;i++)
    {
        ll x,y;
        cin>>x>>y;
        t[x-1]++;
        t[y]--;
    }
    for(ll i=1;i<n;i++)
        t[i]+=t[i-1];
    sort(t,t+n);
    reverse(t,t+n);
    for(ll i=0;i<n;i++)
    {
        out=out+t[i]*a[i];
    }
    cout<<out;

return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define mod 1000000007
#define M INT_MAX;

using namespace std;
ll t[200010];
ll a[200010];
ll out;

int main()
{
    ll n,q,x,y;
    cin.tie(0);
    cin>>n>>q;
    for(ll i=0;i<n;i++) cin>>a[i];
    sort(a,a+n);
    for(ll i=0;i<q;i++)
    {
        cin>>x>>y;
        t[x-1]++;
        t[y]--;
    }
    for(ll i=1;i<n;i++)
        t[i]+=t[i-1];
    sort(t,t+n);
    for(ll i=0;i<n;i++)
    {
        out=out+t[i]*a[i];
    }
    cout<<out<<endl;
 return 0;
}


from sys import stdin

stdin.readline()
num = map(float, stdin.readline().split())

num.sort(reverse=True)
ans = 0

while num:
    ans += sum(num)
    num = num[:len(num)/4]

print int(ans)


from Queue import * # Queue, LifoQueue, PriorityQueue
from bisect import * #bisect, insort
from datetime import *
from collections import * #deque, Counter,OrderedDict,defaultdict
import calendar
import heapq
import math
import copy
import itertools
from math import *

def solver(num):
    if len(num) == 1:
        return (num[0],num[0])

    dan = int(sqrt(len(num)))
    hen = dan/2
    num_block1 = []
    num_block2 = []
    num_block3 = []
    num_block4 = []
    for x in range(hen):
        num_block1 += num[0+dan*x:0+dan*x+hen]
        num_block2 += num[hen+dan*x:hen+dan*x+hen]
        num_block3 += num[dan*(x+hen):dan*(x+hen)+hen]
        num_block4 += num[dan*(x+hen)+hen:dan*(x+hen)+2*hen]

    #print num_block1,num_block2,num_block3,num_block4

    x1,y1 = solver(num_block1)
    x2,y2 = solver(num_block2)
    x3,y3 = solver(num_block3)
    x4,y4 = solver(num_block4)

    maxim = max(x1,x2,x3,x4)
    #print maxim+y1+y2+y3+y4
    return ( maxim,maxim+y1+y2+y3+y4)

if __name__ == "__main__":
    n = input()
    num = map(int,raw_input().split())
    print solver(num)[1]


from Queue import * # Queue, LifoQueue, PriorityQueue
from bisect import * #bisect, insort
from datetime import *
from collections import * #deque, Counter,OrderedDict,defaultdict
import calendar
import heapq
import math
import copy
import itertools
from math import *

def solver():
    n = input()
    num = map(int, raw_input().split())

    num.sort(reverse=True)
    ans = 0

    all_log = int(log(n,4))
    default = -1
    ans += num[0] * (all_log - default)

    for i in range(1,len(num)):
        y = log(i,4)
        x = int(y)
        if x == y:
            default += 1

        ans += num[i] * (all_log-default)
        #print all_log-default,

    print ans

if __name__ == "__main__":

    solver()


from math import log
from sys import stdin
n = input()
num = map(int, stdin.readline().split())
num.sort(reverse=True)
ans = 0
#pow_d = {1024: True, 1: True, 4: True, 4096: True, 64: True, 256: True, 16384: True, 16: True, 4194304: True, 262144: True, 1048576: True, 65536: True}
all_log = int(log(n,4))
default = -1
pow_d=1
ans += num[0] * (all_log - default)
for i in range(1,len(num)):
    if i == pow_d:
        default += 1
        pow_d *= 4
    ans += num[i] * (all_log-default)
print ans


from Queue import * # Queue, LifoQueue, PriorityQueue
from bisect import * #bisect, insort
from datetime import *
from collections import * #deque, Counter,OrderedDict,defaultdict
import calendar
import heapq
import math
import copy
import itertools
from math import *

def solver():
    n = input()
    num = map(int, raw_input().split())
    num.sort(reverse=True)
    ans = 0

    all_log = int(log(n,2))
    default = 1
    ans += num[0] * (all_log - default)
    for i in range(1,len(num)):
        y = log(i,4)
        x = int(y)
        if x == y:
            default += 1

        ans += num[i] * (all_log-default)

    print ans

if __name__ == "__main__":

    solver()


from sys import stdin

def solver():
    stdin.readline()
    num = map(float, stdin.readline().split())

    num.sort(reverse=True)
    ans = 0

    while num:
        ans += sum(num)
        num = num[:len(num)/4]

    print ans

if __name__ == "__main__":

    solver()


from sys import stdin
n = int(stdin.readline())
arr = map(int, stdin.readline().split())
if n == 1:
    print(arr[0])
    exit()
arr.sort(reverse = True)
res = 0
while arr:
    res += sum(arr)
    arr = arr[:len(arr)//4]
print(res)


from sys import stdin
n = int(stdin.readline())
arr = map(int, stdin.readline().split())
if n == 1:
    print(arr[0])
    exit()
arr.sort(reverse = True)
res = 0
while arr:
    res += sum(arr)
    arr = arr[:len(arr)/4]
print(res)


from sys import stdin
n = int(stdin.readline())
arr = map(float, stdin.readline().split())
if n == 1:
    print(int(arr[0]))
    exit()
arr.sort(reverse = True)
res = 0
while arr:
    res += sum(arr)
    arr = arr[:len(arr)/4]
print(int(res))


from sys import stdin
n = int(stdin.readline())
arr = map(float, stdin.readline().split())
if n == 1:
    print(arr[0])
    exit()
arr.sort(reverse = True)
res = 0
while arr:
    res += sum(arr)
    arr = arr[:len(arr)/4]
print(int(res))


from sys import stdin
n = int(stdin.readline())
arr = list(map(int, stdin.readline().split()))
if n == 1:
    print(arr[0])
    exit()
arr.sort(reverse = True)
res = 0
while arr:
    res += sum(arr)
    arr = arr[:len(arr)//4]
print(res)


input()
r = 0
a = map(float, input().split())
a.sort(reverse=1)
while(a):
  r += sum(a)
  a = a[:len(a) / 4]
print r


import sys
#br = open('c.in')
br = sys.stdin
n, r = int(br.readline()), 0
a = sorted(map(int, br.readline().split()), reverse=True)
while(n):
  r += sum(a[:n])
  n /= 4
print r


n, r = int(raw_input()), 0
a = map(int, raw_input().split())
a.sort(reverse=1)
while(n):
  r += sum(a[:n])
  n /= 4
print r


import sys
#br = open('c.in')
br = sys.stdin
m = int(br.readline())
a = sorted(map(int, br.readline().split()))
s, i = [0], 0
while(m):
  s.append(s[i] + sum(a[-m:]))
  m = m >> 2
  i += 1
print s[i]


n, r = int(raw_input()), 0
a = sorted(map(int, raw_input().split()), reverse=True)
while(a):
  r += sum(a)
  a = a[:len(a) / 4]
print r


import sys
#br = open('c.in')
br = sys.stdin
m = int(br.readline())
a = sorted(map(int, br.readline().split()))
n, r = -1, 0
def f(n, a):
  if n == 0:
    return sum(a[-n:])
  return sum(a[-n:]) + f(n - 1, a)
while(m > 0):
  m = m >> 2
  n += 1
print f(n, a)


n = int(raw_input())
a = sorted(map(float, raw_input().split()), reverse=1)
s = 0
while(n):
  s += sum(a[:n])
  n /= 4
print int(s)


n, r = int(raw_input()), 0
a = sorted(map(int, raw_input().split()), reverse=True)
while(n):
  r += sum(a)
  n /= 4
  a = a[:n]
print r


n, r = int(raw_input()), 0
a = sorted(map(int, raw_input().split()), reverse=True)
while(n):
  r += sum(a[:n])
  n /= 4
print r


n = int(raw_input())
a = sorted(map(float, raw_input().split()), reverse=1)
s = 0
while(a):
  s += sum(a)
  a = a[:len(a) / 4]
print int(s)


input()
a = sorted(map(float, raw_input().split()), reverse=1)
s = 0
while(a):
  s += sum(a)
  a = a[:len(a)/4]
print int(s)


n, r = int(raw_input()), 0
a = map(float, raw_input().split())
a.sort(reverse=1)
while(a):
  r += sum(a)
  a = a[:len(a) / 4]
print r


input()
a = map(float, raw_input().split())
a.sort(reverse=1)
s = 0
while a:
  s += sum(a)
  a = a[:len(a)/4]
print int(s)


import sys
#br = open('c.in')
br = sys.stdin
n, r = int(br.readline()), 0
a = map(int, br.readline().split())
a.sort(reverse=1)
while(a):
  r += sum(a)
  a = a[:len(a) / 4]
print r


input()
r = 0
a = map(float, raw_input().split())
a.sort(reverse=1)
while(a):
  r += sum(a)
  a = a[:len(a) / 4]
print r


n, r = int(raw_input()), 0
a = map(int, raw_input().split())
a.sort(reverse=1)
while(a):
  r += sum(a)
  a = a[:len(a) / 4]
print r


import sys
#br = open('c.in')
br = sys.stdin
br.readline()
r = 0
a = map(int, br.readline().split())
a.sort(reverse=1)
while(a):
  r += sum(a)
  a = a[:len(a) / 4]
print r


input()
a = map(int, raw_input().split())
a.sort(reverse=1)
s = 0
while a:
  s += sum(a)
  a = a[:len(a)/4]
print int(s)


import sys
#br = open('c.in')
br = sys.stdin
n = int(br.readline())
a = sorted(map(int, br.readline().split()))
c, d = [0], [0]
for i in range(n):
  c.append(a[i] + c[i])
i = 0
while(n):
  d.append(d[i] + c[-1] - c[-n - 1])
  n = n >> 2
  i += 1
print d[-1]


input()
a = sorted(map(float, raw_input().split()), reverse=1)
s = 0
while a:
  s += sum(a)
  a = a[:len(a)/4]
print int(s)


#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>

using namespace std;

#define all(v) v.begin(), v.end()
#define pb(v, e) v.push_back(e)
#define rall(v) v.rbegin, v.rend()
#define ll long long
#define sz(v) (int) v.size()
#define az(x) (sizeof(x) / sizeof(x[0]))
#define oo (int) 13e7
#define fill(v, e) memset(v, e, sizeof v)

int main()
{
  //freopen("c.in", "r", stdin);
  int n;
  vector<ll> a;
  vector<ll> c;
  cin >> n;
  for(int i = 0; i < n; ++i) {
    int t;
    cin >> t;
    pb(a, t);
  }
  sort(all(a));
  pb(c, 0);
  for(int i = 0; i < n; ++i)
    pb(c, 1ll * a[i] + c[i]);
  ll r = 0ll;
  int m = n;
  while(n) {
    r += c[m] - c[m - n];
    n = n >> 2;
  }
  cout << r << endl;
}


input()
e=sorted(map(int, raw_input().split()), reverse=True)

s=0
p=0
while e:
   s += sum(e)
   e=e[:len(e)/4]
print s


from math import log
n=input()
e=sorted(map(float, raw_input().split()), reverse=True)
c=int(log(n,4))
s=0
p=0
for i in range(c+1):
   r = p + sum(e[int(4**(i-1)*(i>0)):4**i])
   s += r
   p = r
print s


from math import log
n=input()
e=sorted(map(int, raw_input().split()), reverse=True)
c=int(log(n,4))
s=0
for i in range(c+1):
   s += sum(e[:4**i])
print s


input()
e=sorted(map(float, raw_input().split()), reverse=True)

s=0
p=0
while e:
   s += sum(e)
   e=e[:len(e)/4]
print int(s)


from math import log
n=input()
e=sorted(map(int, raw_input().split()), reverse=True)
c=int(log(n,4))
s=0
p=0
for i in range(c+1):
   r = p + sum(e[int(4**(i-1)*(i>0)):4**i])
   s += r
   p = r
print s


n = input()
a = sorted(map(int , raw_input().split()) , reverse = True)
c = int(n == 1)
while n != 1:
    n //= 2
    c += 1
sum = 0
n = len(a)
q = 2
cnt = 1
for i in range(n):
    sum += c * a[i]
    if cnt == q - 1:
        c -= 1
        cnt = 0
        q *= 2
    cnt += 1

print sum


n = input()
a = sorted(map(float , raw_input().split()) , reverse = True)
if n == 1:
    print a[0]
    exit(0)
c = 1
while n != 1:
    n //= 4
    c += 1
sum = 0
n = len(a)
nxt = 1
for i in range(n):
    sum += c * a[i]
    if i + 1 == nxt:
        c -= 1
        nxt *= 4

print int(sum)


n = input()
a = sorted(map(int , raw_input().split()) , reverse = True)
if n == 1:
    print a[0]
    exit(0)
c = 1
while n != 1:
    n //= 4
    c += 1
sum = 0
n = len(a)
nxt = 1
for i in range(n):
    sum += c * a[i]
    if i + 1 == nxt:
        c -= 1
        nxt *= 4

print sum


n = input()
a = sorted(map(int , raw_input().split()) , reverse = True)
if n == 1:
    print a[0]
    exit(0)
c = 1
while n != 1:
    n //= 4
    c += 1
def is_four(x):
    while x % 4 == 0:
        x //= 4
    return x == 1
sum = 0
n = len(a)
for i in range(n):
    sum += c * a[i]
    if is_four(i + 1):
        c -= 1

print sum


n = input()
a = sorted(map(float , raw_input().split()) , reverse = True)
if n == 1:
    print int(a[0])
    exit(0)
c = 1
while n != 1:
    n //= 4
    c += 1
sum = 0
n = len(a)
nxt = 1
for i in range(n):
    sum += c * a[i]
    if i + 1 == nxt:
        c -= 1
        nxt *= 4
q = int(sum)
print int(q)


n = input()
a = sorted(map(float , raw_input().split()) , reverse = True)
answer = 0
while a:
    answer += sum(a)
    a = a[:len(a)//4]

print int(answer)


n = input()
a = sorted(map(float , raw_input().split()) , reverse = True)
if n == 1:
    print a[0]
    exit(0)
c = 1
while n != 1:
    n //= 4
    c += 1
sum = 0
n = len(a)
nxt = 1
for i in range(n):
    sum += c * a[i]
    if i + 1 == nxt:
        c -= 1
        nxt *= 4

print sum


input()
a=map(float,raw_input().split())
a.sort(reverse=1)
s=0
while a:
  s+=sum(a)
  a=a[:len(a)/4]
print int(s)


from sys import stdin
if __name__ == '__main__':
    stdin.readline()
    data = map(int, stdin.readline().split() )

    data.sort(reverse = True)

    ans = 0

    while data:
        ans += sum(data)
        data = data[: len(data)//4]

    print(ans)


from sys import stdin
if __name__ == '__main__':
    stdin.readline()
    data = map(float, stdin.readline().split() )
    data.sort(reverse = True)

    ans = 0
    while data:
        ans += sum(data)
        data = data[: len(data)/4]

    print int(ans)


def str2list(s):
    l2 = list(map(int, s.split() ) )
#    print(l2)
    return l2

def int_pow(base, index):
    if index <= 0:
        return 1
    result = 1
    while index > 1:
        if index % 2 == 1:
            result *= base
        base *= base
        index = int(index / 2)
    result *= base
    return result

def log4(x):
    index = 0
    y = 1
    while y < x:
        y *= 4
        index += 1
    return index

import array
if __name__ == '__main__':
#    print( log4(256) )
#    print( int_pow(3, 0) )
    tmp = raw_input()
    mar = int(tmp)
    tmp = raw_input()
    data = str2list(tmp)
#    print(data)
    N = log4(mar)

    #print(data)
    #print(N)

#    data.append(10**9 + 1)
    data.sort(reverse = True)
#    dat = array.array('Q', data)

    ans = 0

    while data:
        ans += sum(data)
        data = data[: len(data)//4]

    print(ans)


from sys import stdin
if __name__ == '__main__':
    stdin.readline()
    data = map(int, stdin.readline().split() )
    data.sort(reverse = True)

    ans = 0
    while data:
        ans += sum(data)
        data = data[: len(data)/4]

    print ans


if __name__ == '__main__':
    tmp = raw_input()
    mar = int(tmp)
    tmp = raw_input()
    data = map(int, tmp.split() )

    data.sort(reverse = True)

    ans = 0

    while data:
        ans += sum(data)
        data = data[: len(data)/4]

    print(ans)


if __name__ == '__main__':
    tmp = raw_input()
    mar = int(tmp)
    tmp = raw_input()
    data = list(map(int, tmp.split() ) )

    data.sort(reverse = True)

    ans = 0

    while data:
        ans += sum(data)
        data = data[: len(data)/4]

    print(ans)


if __name__ == '__main__':
    raw_input()
    tmp = raw_input()
    data = map(int, tmp.split() )

    data.sort(reverse = True)

    ans = 0

    while data:
        ans += sum(data)
        data = data[: len(data)/4]

    print(ans)


n = int(input()) // 4
t = map(int, raw_input().split())
a, b = t[:2 * n], t[2 * n:]
a.sort(reverse = True)
b.sort(reverse = True)
t = t[:n]

i, j, k = 0, 0
while k < n:
    if a[i] > b[j]:
        t[k] = a[i]
        i += 1
        k += 1
    else:
        t[k] = b[j]
        j += 1
        k += 1

s, k = 0, 1
while k < n:
    s += sum(t[:k])
    k *= 4
print(s + 2 * sum(t[:n]) + sum(a[i:]) + sum(b[j:]))


n = int(raw_input()) // 4
t = list(map(int, raw_input().split()))
a, b = t[:2 * n], t[2 * n:]
a.sort(reverse = True)
b.sort(reverse = True)
t = t[:n]

i, j, k = 0, 0
while k < n:
    if a[i] > b[j]:
        t[k] = a[i]
        i += 1
        k += 1
    else:
        t[k] = b[j]
        j += 1
        k += 1

s, k = 0, 1
while k < n:
    s += sum(t[:k])
    k *= 4
print(s + 2 * sum(t[:n]) + sum(a[i:]) + sum(b[j:]))


n = int(raw_input()) // 4
t = map(int, raw_input().split())
a, b = t[:2 * n], t[2 * n:]
a.sort(reverse = True)
b.sort(reverse = True)
t = t[:n]

i, j, k = 0, 0
while k < n:
    if a[i] > b[j]:
        t[k] = a[i]
        i += 1
        k += 1
    else:
        t[k] = b[j]
        j += 1
        k += 1

s, k = 0, 1
while k < n:
    s += sum(t[:k])
    k *= 4
print (s + 2 * sum(t[:n]) + sum(a[i:]) + sum(b[j:]))


def f(x):
    k = 1
    while x > k: k *= 4
    return k

from sys import stdin
n = int(stdin.readline()) - 1
t = map(int, stdin.readline().split())

k, s = f(n) // 4, sum(t)
t.sort(reverse = True)

while k:
    t = t[:k]
    s += sum(t)
    k //= 4
print(int(s))


from sys import stdin
n = int(stdin.readline()) // 4
t = map(float, stdin.readline().split())

if n == 0: print(int(t[0]))
else:
    k = 2 * n
    a, b = t[:k], t[k:]
    a.sort(reverse = True)
    b.sort(reverse = True)

    ans, s, k, i, j = 0, 0, 1, 0, 0
    while i + j < n:
        while i + j < k:
            if a[i] > b[j]:
                s += a[i]
                i += 1
            else:
                s += b[j]
                j += 1
        ans += s
        k *= 4

    print(int(ans + s + sum(a[i:]) + sum(b[j:])))


def f(x):
    k = 1
    while x > k: k *= 4
    return k

from sys import stdin
n = int(stdin.readline()) - 1
t = stdin.readline().split()

k, s = f(n) // 4, sum(t)
t.sort(reverse = True)
t = [int(i) for i in t]
while k:
    t = t[:k]
    s += sum(t)
    k //= 4
print(int(s))


def f(x):
    k = 1
    while x > k: k *= 4
    return k

from sys import stdin
n = int(stdin.readline()) - 1
t = list(map(float, stdin.readline().split()))

k, s = f(n) // 4, sum(t)
t.sort(reverse = True)

while k:
    t = t[:k]
    s += sum(t)
    k //= 4
print(int(s))


n = int(raw_input()) // 4
t = map(float, raw_input().split())

if n == 0: print(int(t[0]))
else:
    k = 2 * n
    a, b = t[:k], t[k:]
    a.sort(reverse = True)
    b.sort(reverse = True)

    ans, s, k, i, j = 0, 0, 1, 0, 0
    while i + j < n:
        while i + j < k:
            if a[i] > b[j]:
                s += a[i]
                i += 1
            else:
                s += b[j]
                j += 1
        ans += s
        k *= 4

    print(int(ans + s + sum(a[i:]) + sum(b[j:])))


n = int(raw_input()) // 4
t = map(int, raw_input().split())
a, b = t[:2 * n], t[2 * n:]
a.sort(reverse = True)
b.sort(reverse = True)
t = t[:n]

i, j, k = 0, 0
while k < n:
    if a[i] > b[j]:
        t[k] = a[i]
        i += 1
        k += 1
    else:
        t[k] = b[j]
        j += 1
        k += 1

s, k = 0, 1
while k < n:
    s += sum(t[:k])
    k *= 4
print(s + 2 * sum(t[:n]) + sum(a[i:]) + sum(b[j:]))


n = int(raw_input()) / 4
t = map(int, raw_input().split())
a, b = t[:2 * n], t[2 * n:]
a.sort(reverse = True)
b.sort(reverse = True)
t = t[:n]

i, j, k = 0, 0, 0
while k < n:
    if a[i] > b[j]:
        t[k] = a[i]
        i += 1
        k += 1
    else:
        t[k] = b[j]
        j += 1
        k += 1

s, k = 0, 1
while k < n:
    s += sum(t[:k])
    k *= 4
print (s + 2 * sum(t[:n]) + sum(a[i:]) + sum(b[j:]))


def f(x):
    k = 1
    while x > k: k *= 4
    return k

from sys import stdin
n = int(stdin.readline()) - 1
t = map(float, stdin.readline().split())

k, s = f(n) // 4, sum(t)
t.sort(reverse = True)

while k:
    t = t[:k]
    s += sum(t)
    k //= 4
print(int(s))


n = int(raw_input())
vals = list(map(int, raw_input().split()))
vals.sort(reverse=1)
#vals.reverse()
b = 0
while n > 0:
 vals = vals[:n]
 b += sum(vals)
 n = n>>2
print(b)


n = int(input())
vals = map(int, input().split())
vals.sort(reverse=1)
#vals.reverse()
b = 0
while n > 0:
 vals = vals[:n]
 b += sum(vals)
 n = n>>2
print(b)


n = int(raw_input())
vals = map(float, raw_input().split())
vals.sort(reverse=1)
#vals.reverse()
b = 0
while n > 0:
 vals = vals[:n]
 b += sum(vals)
 n = n>>2
print(int(b))


n = int(raw_input())
vals = map(int, raw_input().split())
vals.sort(reverse=1)
#vals.reverse()
b = 0
while n > 0:
 vals = vals[:n]
 b += sum(vals)
 n = n>>2
print(b)


input()
a=map(float,raw_input().split())
a.sort(reverse=1)
s=0
while a:
  s+=sum(a)
  a=a[:len(a)/4]
print int(s)


n = input()
c = map(int,raw_input().split())
c.sort()
res = c[-1]
n -= 4
while(n >= 0):
	res += sum(c[n:])
	n-=4
print res


input()
a = map(float, raw_input().split())
a.sort(reverse=1)
s = 0
while a:
  s += sum(a)
  a = a[:len(a)/4]
print int(s)


n = input()
c = map(int,raw_input().split())
c.sort(reverse = 1)
res = 0
while(n >= 1):
	res += sum(c[:n])
	n/=4
print res


from sys import stdin
n = input()
num = map(float, raw_input().split(' ') )
num.sort(reverse=True)
s = 0;
while num:
        s += sum(num)
        num = num[:len(num)>>2]
print int(s)


s = raw_input()
n = len(s)
dp = [0]*(n+1)

for i in xrange(1, n):
        dp[i] = dp[i-1] if s[i]!=s[i-1] else dp[i-1]+1
for i in xrange(input() ):
        l, r = map(int, raw_input().split() )
        print dp[r-1]-dp[l-1]


n=int(raw_input())
num = map(int, raw_input().split() )
Max = max(num)
print Max if n==1 else Max + sum(num)


from sys import stdin
n = int( stdin.readline() )
num = map(float, stdin.readline().split(' ') )
num.sort(reverse=True)
s = 0;
while num:
        s += sum(num)
        num = num[:len(num)>>2]
print int(s)


import bisect
n = input()
num = map(int, raw_input().split() )
if n == 1:
        print num[0]
else :
        a = sorted(num[:4])
        for v in num[4:]:
                if v > a[0]:
                        bisect.insort_left(a, v); a.pop()
        print sum(a)+a[3]
~


import bisect
n = input()
num = map(int, raw_input().split() )
if n == 1:
        print num[0]
else :
        a = sorted(num[:4])
        for v in num[4:]:
                if v > a[0]:
                        bisect.insort_left(a, v); a.pop()
        print sum(a)+a[3]


from sys import stdin
n = int( stdin.readline() )
num = map(int, stdin.readline().split(' ') )
num.sort(reverse=True)
s = 0;
while num:
        s += sum(num)
        num = num[:len(num)>>2]
print s


from sys import stdin
n = int( stdin.readline() )
num = map(int, stdin.readline().split(' ') )
num.sort(reverse=True)
s = 0; N = len(num)
while N>1:
        s += sum(num)
        N = len(num)/4
        num = num[:N]
print s+num[0]


/* practice with Dukkha */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

#define N	2000000

void srand_() {
	struct timeval tv;

	gettimeofday(&tv, NULL);
	srand(tv.tv_sec ^ tv.tv_usec);
}

int rand_(int n) {
	return (rand() * 76543LL + rand()) % n;
}

int compare(const void *a, const void *b) {
	int ia = *(int *) a;
	int ib = *(int *) b;

	return ib - ia;
}

int main() {
	static int aa[N];
	int n, i, j, tmp;
	long long ans;

	srand_();
	scanf("%d", &n);
	for (i = 0; i < n; i++)
		scanf("%d", &aa[i]);
	for (i = 0; i < n; i++) {
		j = rand_(i + 1);
		tmp = aa[i], aa[i] = aa[j], aa[j] = tmp;
	}
	qsort(aa, n, sizeof *aa, compare);
	ans = 0;
	while (n >= 1) {
		for (i = 0; i < n; i++)
			ans += aa[i];
		n /= 4;
	}
	printf("%lld\n", ans);
	return 0;
}


/* https://codeforces.com/contest/313/submission/58619807 (rainboy) */
#include <stdio.h>
#include <stdlib.h>

#define N 2000000

int compare(const void *a, const void *b) {
	int ia = *(int *) a;
	int ib = *(int *) b;

	return ib - ia;
}

int main() {
	static int aa[N];
	int n, i;
	long long ans;

	scanf("%d", &n);
	for (i = 0; i < n; i++)
		scanf("%d", &aa[i]);
	qsort(aa, n, sizeof *aa, compare);
	ans = 0;
	while (n > 0) {
		for (i = 0; i < n; i++)
			ans += aa[i];
		n /= 4;
	}
	printf("%lld\n", ans);
	return 0;
}


// for 2x2 beauty is S + m
// for 4x4 - sum of submatrices will be S + sum(m2) plus extra m4
// for 16x16 similarly S + sum(m2) + sum(m4) + m16
// so the strategy would be to sort numbers descending and sum [0..M] where M is current submatrix size

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_N 2000000
static int _a[MAX_N];

static int compare_int(const void* a, const void* b) {
    return *(const int*)b - *(const int*)a;
}

int main() {
    int N; scanf("%d\n", &N);
    for(int i = 0 ; i < N ; ++i) scanf("%d\n", &_a[i]);
    qsort(_a, N, sizeof(int), compare_int);

    int64_t B = 0;
    for( ; N > 0 ; N /= 4) {
        for(int i = 0 ; i < N ; ++i)
            B += _a[i];
    }

    printf("%" PRId64 "\n", B);
}


    #include<stdio.h>
    #include<stdlib.h>
    long long int compare(long long int *q,long long int *r)
    {
        return *q-*r;
    }
    int main()
    {
       long long int a,i,sum=0,j;
        scanf("%lld",&a);
       long long int b[a];
        for(i=0;i<a;i++)
        {
            scanf("%lld",&b[i]);
        }
        if(a==1)
        {
            printf("%lld",b[0]);
            return 0;
        }
        qsort(b,a,sizeof(long long int),compare);
        for(i=1;i<=a;i*=4)
		for(j=1;j<=i;j++)
			sum+=b[a-j];
        printf("%lld",sum);
    }


#include<stdio.h>
#include<stdlib.h>
long long int compare(long long int *q,long long int *r)
{
    return *r-*q;
}
int main()
{
   long long int a,i,sum=0;
    scanf("%lld",&a);
   long long int b[a];
    for(i=0;i<a;i++)
    {
        scanf("%lld",&b[i]);
    }
    if(a==1)
    {
        printf("%lld",b[0]);
        return 0;
    }
    qsort(b,a,sizeof(long long int),compare);
    sum=b[0];
    for(i=0;i<=3;i++)
    {
        sum=sum+b[i];
    }
    printf("%lld",sum);
}


#include <stdio.h>
void merge(long long int a[],long long int l,long long int m,long long int r)
{
    long long int i,j,k,d1,d2;
    d1=m-l+1;
    d2=r-m;
    long long int le[d1],ri[d2];
    for(i=0; i<d1; i++)
    {
        le[i]=a[l+i];
    }
    for(i=0; i<d2; i++)
    {
        ri[i]=a[m+i+1];
    }
    i=j=0;
    k=l;
    while(i<d1&&j<d2)
    {
        if(le[i]<ri[j])
        {
            a[k]=le[i];
            i++;
            k++;
        }
        else
        {
            a[k]=ri[j];
            j++;
            k++;
        }
    }
    while(i<d1)
    {
        a[k]=le[i];
        i++;
        k++;
    }
    while(j<d2)
    {
        a[k]=ri[j];
        j++;
        k++;
    }
}
void msort(long long int a[],long long int l,long long int r)
{
    if(l<r)
    {
        long long int mid;
        mid=l+(r-l)/2;
        msort(a,l,mid);
        msort(a,mid+1,r);
        merge(a,l,mid,r);
    }
}
int main()
{
    long long int n,m,i,s=0,k,j,l,f,z=1;
    scanf("%lld",&n);
    k=n;
    for(f=0;f<13;f++)
    {
        if(k==1)
        {
            break;
        }
        k=k/4;
    }
    long long int A[n],B[n],C[n];
    for(i=0; i<n; i++)
    {
        scanf("%lld",&A[i]);
        s=s+A[i];
    }
    msort(A,0,n-1);
    for(j=0;j<f;j++)
    {
        for(l=1;l<=z;l++)
        {
            s=s+A[n-l];
        }
        z=z*4;
    }
    printf("%lld\n",s);
    return 0;
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace A
{
    class Program
    {
        private static int[] a;

        private static TextReader GetFileTextReader()
        {
            return File.OpenText(@"..\..\input.txt");
        }

        private static TextWriter GetFileTextWriter()
        {
            return File.CreateText(@"..\..\output.txt");
        }

        private static TextReader GetConsoleTextReader()
        {
            return Console.In;
        }

        private static TextWriter GetConsoleTextWriter()
        {
            return Console.Out;
        }

        static void Main(string[] args)
        {
            using (TextReader reader = GetConsoleTextReader())
            {
                using (TextWriter writer = GetConsoleTextWriter())
                {
                    int n = int.Parse(reader.ReadLine());

                    a = new int[n];

                    string[] s = reader.ReadLine().Split(" ".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < n; i++)
                    {
                        a[i] = int.Parse(s[i]);
                    }

                    Random r = new Random();

                    int[] array = a.OrderBy(_ => r.NextDouble()).ToArray();
                    Array.Sort(array);

                    long result = 0;
                    for (int i = n; i > 0; i /= 4)
                    {
                        for (int j = n - 1; j >= n - i; j--)
                        {
                            result += array[j];
                        }
                    }

                    writer.WriteLine(result);

                }
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeForces
{
    class С
    {
        public void Run()
        {
            var r = 0;
            var n = int.Parse(Console.ReadLine());
            var m = Console.ReadLine().Split(' ').Select(i => int.Parse(i)).ToArray();
            do{
              r += m.Take(n).Sum();
              n /= 4;
            } while (n > 0);
            Console.WriteLine(r);
        }
    }

    class Programm
    {
        static void Main(string[] args)
        {
            new С().Run();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeForces
{
    class A
    {
        public void Run()
        {
            var n = Console.ReadLine();
            var m = new long[3];
            m[0] = long.Parse(n);
            m[1] = long.Parse(n.Remove(n.Length - 1, 1));
            m[2] = long.Parse(n.Remove(n.Length - 2, 1));

            Console.Write(m.Max());
        }
    }

    class B
    {
        public void Run()
        {
            var s = Console.ReadLine();
            var m = int.Parse(Console.ReadLine());

            var part = new List<int>();
            part.Add(0);
            for (int j = 0; j < s.Length - 1; j++)
                part.Add(part[part.Count - 1] + ((s[j] == s[j + 1]) ? 1 : 0));

            for (int i = 0; i < m; i++)
            {
                var lr = Console.ReadLine().Split(' ');
                int l = int.Parse(lr[0])-1;
                int r = int.Parse(lr[1])-1;

                Console.WriteLine(part[r] - part[l]);
            }

        }
    }

    class C
    {
        public void Run()
        {
            long r = 0;
            int n = int.Parse(Console.ReadLine());
            long[] m = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).OrderByDescending(x => x).ToArray();
            do
            {
                r += m.Take(n).Sum();
                n /= 4;
            } while (n > 0);
            Console.WriteLine(r);
        }
    }

    class Programm
    {
        static void Main(string[] args)
        {
            new C().Run();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeForces
{
    class A
    {
        public void Run()
        {
            var n = Console.ReadLine();
            var m = new long[3];
            m[0] = long.Parse(n);
            m[1] = long.Parse(n.Remove(n.Length - 1, 1));
            m[2] = long.Parse(n.Remove(n.Length - 2, 1));

            Console.Write(m.Max());
        }
    }

    class B
    {
        public void Run()
        {
            var s = Console.ReadLine();
            var m = int.Parse(Console.ReadLine());

            var part = new List<int>();
            part.Add(0);
            for (int j = 0; j < s.Length - 1; j++)
                part.Add(part[part.Count - 1] + ((s[j] == s[j + 1]) ? 1 : 0));

            for (int i = 0; i < m; i++)
            {
                var lr = Console.ReadLine().Split(' ');
                int l = int.Parse(lr[0])-1;
                int r = int.Parse(lr[1])-1;

                Console.WriteLine(part[r] - part[l]);
            }

        }
    }

    class C
    {
        public void Run()
        {
            long r = 0;
            int n = int.Parse(Console.ReadLine());
            long[] m = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).OrderByDescending(x => x).ToArray();
            do
            {
                r += m.Take(n).Sum();
                n /= 4;
            } while (n > 0);
            Console.WriteLine(r);
        }
    }

    class Programm
    {
        static void Main(string[] args)
        {
            new B().Run();
            Console.ReadLine();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeForces
{
    class С
    {
        public void Run()
        {
            var r = 0;
            var n = int.Parse(Console.ReadLine());
            var m = Console.ReadLine().Split(' ').Select(i => int.Parse(i)).OrderByDescending(x => x).ToArray();
            do{
              r += m.Take(n).Sum();
              n /= 4;
            } while (n > 0);
            Console.WriteLine(r);
        }
    }

    class Programm
    {
        static void Main(string[] args)
        {
            new С().Run();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeForces
{
    class С
    {
        public void Run()
        {
            long r = 0;
            long n = int.Parse(Console.ReadLine());
            long[] m = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).OrderByDescending(x => x).ToArray();
            do{
              r += m.Take(n).Sum();
              n /= 4;
            } while (n > 0);
            Console.WriteLine(r);
        }
    }

    class Programm
    {
        static void Main(string[] args)
        {
            new С().Run();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeForces
{
    class A
    {
        public void Run()
        {
            var n = Console.ReadLine();
            var m = new long[3];
            m[0] = long.Parse(n);
            m[1] = long.Parse(n.Remove(n.Length - 1, 1));
            m[2] = long.Parse(n.Remove(n.Length - 2, 1));

            Console.Write(m.Max());
        }
    }

    class B
    {
        public void Run()
        {
            var s = Console.ReadLine();
            var m = int.Parse(Console.ReadLine());

            var part = new List<int>();
            part.Add(0);
            for (int j = 0; j < s.Length - 1; j++)
                part.Add(part[part.Count - 1] + ((s[j] == s[j + 1]) ? 1 : 0));

            for (int i = 0; i < m; i++)
            {
                var lr = Console.ReadLine().Split(' ');
                int l = int.Parse(lr[0])-1;
                int r = int.Parse(lr[1])-1;

                Console.WriteLine(part[r] - part[l]);
            }

        }
    }

    class C
    {
        public void Run()
        {
            long r = 0;
            int n = int.Parse(Console.ReadLine());
            long[] m = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).OrderByDescending(x => x).ToArray();
            do
            {
                r += m.Take(n).Sum();
                n /= 4;
            } while (n > 0);
            Console.WriteLine(r);
        }
    }

    class Programm
    {
        static void Main(string[] args)
        {
            new B().Run();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; //for StreamReader & Writer

namespace CodeForces
{
    class R186_Div2_C
    {
        static void Main(string[] args)
        {
            //TextReader reader = new StreamReader("../../input_genC.txt");
            int n = int.Parse(Console.ReadLine());
            string[] s = Console.ReadLine().Split();
            int[] a = new int[n];
            long total = 0;
            for (int i = 0; i < n; i++)
            {
                a[i] = int.Parse(s[i]);
                total += a[i];
            }

            Random rnd = new Random(Environment.TickCount);
            int ra, temp;
            for (int i = 0; i < n; i++)
            {
                ra = rnd.Next(0, n);
                temp = a[i];
                a[i] = a[ra];
                a[ra] = temp;
            }
            Array.Sort(a);
            Array.Reverse(a);

            int num = 1;
            int prod = 1;
            while (prod < n)
            {
                num++;
                prod *= 4;
            }

            long sum = 0;
            prod = 1;
            for (int i = 0; i < num-1; i++)
            {
                for (int j = 0; j < prod; j++)
                    sum += a[j];
                prod *= 4;
            }
            sum += total;

            Console.WriteLine(sum);
        }
    }
}


using System;
using System.Collections.Generic;

public sealed class Program {

  public Program() {
    Int32 n = ReadInt(), i, j, k, p;
    Int32[] maj = new Int32[n], mult = new Int32[n];
    for (p = 1, j = 1; p != n; p *= 4, ++j) { }
    for (i = 0, k = 1; j != 0; --j, k *= 4) {
      for (; i < k; mult[i++] = j) { }
    }
    for (i = 0; i < n; maj[i++] = ReadInt()) { }
    Array.Sort(maj);
    Array.Reverse(maj);
    Int64 result = 0;
    for (i = 0; i < n; ++i) {
      result += Math.BigMul(maj[i], mult[i]);
    }
    Console.WriteLine(result);
  }

  // stuff cutline

  static Int32 ReadInt() {
    Boolean neg = false;
    Int32 ch, ans = 0;
    do {
      ch = Console.Read();
      neg |= ch == (Int32)'-';
    } while (!Char.IsDigit((Char)ch));
    do {
      ans = ans * 10 + (ch & 0xf);
      ch = Console.Read();
    } while (Char.IsDigit((Char)ch));
    return neg ? -ans : ans;
  }

  public static void Main() {
#if DEBUG
    Console.SetIn(new System.IO.StreamReader("..\\..\\in.txt"));
#endif
    var root = new Program();
    Console.Out.Flush();
  }

}


// 2018-10-12 09:57
fn main() {
    let n: i64 = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let mut v: Vec<i64> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().split(" ").map(|s| s.parse::<i64>().unwrap()).collect()
    };
    v.sort_by(|i, j| j.cmp(i));

    let mut total = vec![0;v.len() + 1];
    for i in 1..v.len() + 1 {
        total[i] = total[i - 1] + v[i - 1]
    }

    let mut ret = v[0];
    let mut i = 4;
    while i < n + 1 {
        ret += total[i as usize];
        i *= 4;
    }
    println!("{:?}", ret);
}


// 2018-10-12 09:57
fn main() {
    let n: i32 = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let mut v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().split(" ").map(|s| s.parse::<i32>().unwrap()).collect()
    };
    v.sort_by(|i, j| j.cmp(i));

    let mut total = vec![0;v.len() + 1];
    for i in 1..v.len() + 1 {
        total[i] = total[i - 1] + v[i - 1]
    }

    let mut ret = v[0];
    for i in (4..n + 1).step_by(4) {
        ret += total[i as usize];
    }
    println!("{:?}", ret);
}


from sys import stdin

rints = lambda: [int(x) for x in stdin.readline().split()]
n, a, ans, ma = int(input()), rints()[::-1], 0, 0

for i in range(n):
    ma -= 1
    if ma < 0:
        ans += 1

    if a[i] > ma:
        ma = a[i]

print(ans)


n = input()
inp = [int(x) for x in raw_input().split()][-1::-1]
dp = [0]*n
for i in xrange(n):
    if(inp[i]!=0):
        if(i+1<n):
            dp[i+1]+=1
        if(i+1+inp[i] < n):
            dp[i+1+inp[i]]-=1
ans = 1
for i in xrange(1,n):
    dp[i]+=dp[i-1]
    if(dp[i]==0):
        ans+=1
print ans


raw_input()
tab = map(int, raw_input().split())
mx = 0
ans = 0
for q in tab[::-1]:
    if mx == 0:
        ans += 1
    mx = max(q, mx-1)
print ans


 raw_input()
tab = map(int, raw_input().split())
mx = 0
ans = 0
for q in tab[::-1]:
    if mx == 0:
        ans += 1
    mx = max(q, mx-1)
print ans


n = int(raw_input())

l = map(int, raw_input().split())

p = sorted([max(0, i - l[i]) for i in xrange(n)])
j, t = 0, 0

ans = 0

for i in xrange(n):
	while j < n and p[j] <= i:
		t += 1
		j += 1
	t -= 1
	if not t:
		ans += 1

print ans


# status=not_done
import sys
lines = sys.stdin.read().splitlines()
N = int(lines[0])
a = list(map(int, lines[1].split(' ')))

reach = N
count = 0
for i in range(N - 1, -1, -1):
    if i < reach:
        count += 1
    reach = min(reach, i - a[i])
print count


n = int(input())
a = [int(x) for x in input().split()]
a.reverse()
s = set()
for i in range(n):
    for j in range(i + 1, min(i + a[i] + 1, n)):
        s.add(j)
print(n - len(s))


n = int(input())
a = [int(x) for x in input().split()]
a.reverse()
k = 0
ans = n
for i in range(n):
    if k > 0:
        ans -= 1
    k -= 1
    k = max(k, a[i])
print(ans)


import sys
input = sys.stdin.readline
n = int(input())
a = [int(x) for x in input().split()]
a.reverse()
k = 0
ans = n
for i in range(n):
    if k > 0:
        ans -= 1
    k -= 1
    k = max(k, a[i])
print(ans)


n = int(input())
a = [int(x) for x in input().split()]
a.reverse()
for i in range(n):
    if a[i] > 0:
        for j in range(i + 1, min(i + a[i] + 1, n)):
            a[j] = min(a[j] - a[i] + i + 1, n - j - 1)
ans = n
for x in a:
    if x > 0:
        ans -= x
print(max(ans, 1))


a=int(input())
z=list(map(int,input().split()))
z=z[::-1]
l=0
r=0
count=0

while(l<=r and r<len(z)):

    if(l==r):

        if(r+z[l]+1<len(z)):
            count+=z[l]
            r+=z[l]+1
        else:
            count+=len(z)-r-1
            r=len(z)
        l+=1
    else:
        if(z[l]<r-l):
            l+=1
        else:
            if(r+(z[l]-(r-l-1))<len(z)):

                count+=z[l]-(r-l-1)
                r+=z[l]-(r-l-1)
            else:
                count+=len(z)-r
                r=len(z)
            l+=1
print(len(z)-count)


def read():
	return list(map(int, input().split()))

def main():
	n = int(input())
	l = read()
	last = n
	alive = 0
	for i in range(n - 1, -1, -1):
		if l[i] > 0:
			if last <= 0:
				break
			if last <= i - l[i]:
				continue
			elif last <= i:
				last = i - l[i]
			else:
				alive += last - i
				last = i - l[i]
	if last > 0:
		alive += last
	return alive

print(main())


def read():
	return list(map(int, input().split()))

def main():
	n = int(input())
	l = read()
	last = n
	alive = 0
	for i in range(n - 1, -1, -1):
		if l[i] > 0:
			if i - l[i] <= 0:
				alive += last - i
				last = 0
				break
			if last <= i - l[i]:
				continue
			elif last <= i:
				last = i - l[i]
			else:
				alive += last - i
				last = i - l[i]
	if last > 0:
		alive += last
	return alive

print(main())


n = int(input())
L = [int(i) for i in input().split()]

j = n - 1
x = j - L[j]
i = j
vivos = n
while i>0:
    i -= 1
    if x > j - L[j]: x = j - L[j]
    if x <= i: vivos -= 1
    j-=1

print(vivos)


n = int(input())
fila = [int(i) for i in input().split()]

j = n - 1

mortos = []
while 1:
    i = max(j - fila[j], 0)
    mortos+=fila[i:j]
    j-= max(fila[j], 1)
    if i == 0: break

print(n - len(mortos))


#------------------------------what is this I don't know....just makes my mess faster--------------------------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#----------------------------------Real game starts here--------------------------------------
'''

___________________THIS IS AESTROIX CODE________________________
                       KARMANYA GUPTA

'''
#_______________________________________________________________#
import math
def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x-1)
def lower_bound(li, num): #return 0 if all are greater or equal to
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer #index where x is not less than num
def upper_bound(li, num): #return n-1 if all are small or equal
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2

		if li[middle] <= num:
			answer = middle
			start = middle + 1

		else:
			end = middle - 1
	return answer #index where x is not greater than num

def abs(x):
	return x if x >=0 else -x
def binary_search(li, val, lb, ub):
	ans = 0
	while(lb <= ub):
		mid = (lb+ub)//2
		#print(mid, li[mid])
		if li[mid] > val:
			ub = mid-1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans
#_______________________________________________________________#

n = int(input())
guilty = list(map(int, input().split()))
pref = [0]*n
for i in range(1,n):
	if guilty[i] == 0:
		continue
	if guilty[i] > i:
		pref[0] += 1
	else:
		pref[i-guilty[i]] += 1
	pref[i] -= 1
for i in range(1,n):
	pref[i] += pref[i-1]
print(pref.count(0))


n = int(input())
L = [int(i) for i in input().split()]
su = 0
l = n
for i in range(n - 1, 1, -1):
    nl = max(i - L[i], 0)
    if l > nl:
        if i < l:
            su += i - nl
        else:
            su += l - nl
        l = nl
    if l <= 0:
        break
print(n - su)


n = int(input())
L = [int(i) for i in input().split()]
su = 0
l = n
for i in range(n - 1, 0, -1):
    nl = max(i - L[i], 0)
    if l > nl:
        if i < l:
            su += i - nl
        else:
            su += l - nl
        l = nl
    if l <= 0:
        break
print(n - su)


def solve():
    n = int(input())
    al = [int(i) for i in input().split()]
    cl = [0]*n

    for i in range(n - 1, -1, -1):
        if i - al[i] <= 0:
            cl[0] = min(cl[0], -i)
        else:
            cl[i - al[i]] = min(-al[i], cl[i - al[i]])

    idx = 0
    ans = 1
    while idx < n - 1:
        if cl[idx] != 0:
            t = -cl[idx]
            while t > 0 and idx < n - 1:
                idx += 1
                t -= 1
                t = max(t, -cl[idx])
        else:
            ans += 1
            idx += 1
    print(ans)

if __name__=="__main__":
    solve()


n = int(input())
L = [int(i) for i in input().split()]
pomoika = 0
l = n
for i in range(n - 1, 0, -1):
    nl = max(i - L[i], 0)
    if l > nl:
        if i < l:
            pomoika += i - nl
        else:
            pomoika += l - nl
        l = nl
    if l <= 0:
        break
print(n - pomoika)


def main():
    n = int(input())
    arr = list(map(int, input().split()))

    cnt = 1
    minIdx = len(arr) - 1

    for curIdx in range(len(arr) - 1, -1, -1):

        if curIdx < minIdx:
            cnt += 1

        minIdx = min(minIdx, curIdx - arr[curIdx])

    print(cnt)

if __name__ == "__main__":
    main()


def main():
    n = int(input())
    arr = list(map(int, input().split()))

    curIdx = len(arr) - 2
    cnt = 1
    maxIdx = curIdx + 1

    while curIdx >= 0:
        if arr[maxIdx] < arr[curIdx]:
            maxIdx = curIdx
        if arr[maxIdx] == 0:
            cnt += 1

        curIdx -= 1
        arr[maxIdx] = max(arr[maxIdx] - 1, 0)

    print(cnt)

if __name__ == "__main__":
    main()


n = int(input())
a = [int(x) for x in input().split()]
alive = 0
minKillIndex = n
for i in range(n - 1, -1, -1):
    if i < minKillIndex:
        alive += 1
    minKillIndex = min(i - a[i], minKillIndex)

print(alive)


n = int(input())
*a, = map(int, input().split())
cnt, j = 0, n
for i in range(n - 1, -1, -1):
    if j > i:
        cnt += 1
    j = min(j, i - a[i])
print(cnt)


n=int(input())
l=list(map(int,input().split()))
j=l[n-1]-1
for i in range(n-2,-1,-1):
    j=max(j,l[i])
    l[i]=j
    j-=1
cnt=l.count(0)
if l[n-1]!=0 and l[0]!=0:
    cnt+=1
print(cnt)


n=int(input())
l=list(map(int,input().split()))
j=l[n-1]-1
for i in range(n-2,-1,-1):
    j=max(j,l[i])
    l[i]=j
    j-=1
cnt=l.count(0)
if l[n-1]!=0:
    cnt+=1
print(cnt)


n=int(input())
l=list(map(int,input().split()))
j=l[n-1]-1
for i in range(n-2,-1,-1):
    j=max(j,l[i])
    l[i]=j
    j-=1
l[n-1]=0
cnt=l.count(0)
print(cnt)


n=int(input())
l=list(map(int,input().split()))
cnt=0
j=l[n-1]-1
for i in range(n-2,-1,-1):
    j=max(j,l[i])
    l[i]=j
    j-=1
for i in range(1,n):
    if l[i]==0:
        cnt+=1
print(cnt+1)


class CodeforcesTask892BSolution:
    def __init__(self):
        self.result = ''
        self.n = 0
        self.claws = []

    def read_input(self):
        self.n = int(input())
        self.claws = [int(x) for x in input().split(" ")]

    def process_task(self):
        kill = False
        living = 0
        kill_range = self.n + 1
        for x in range(self.n, 0, -1):
            if x < kill_range:
                kill = False
            if not kill:
                living += 1
            if self.claws[x - 1]:
                kill = True
                kill_range = min(kill_range, x - self.claws[x - 1])
        self.result = str(living)

    def get_result(self):
        return self.result

if __name__ == "__main__":
    Solution = CodeforcesTask892BSolution()
    Solution.read_input()
    Solution.process_task()
    print(Solution.get_result())


from sys import stdin, stdout
from random import randrange

n = int(stdin.readline())
counting = [0 for i in range(n + 10)]
values = list(map(int, stdin.readline().split()))

for i in range(n):
    v = values[i]
    counting[max(0, i - v)] += 1
    counting[i] -= 1

cnt = n
for i in range(n):
    counting[i] += counting[i - 1]

    if counting[i]:
        cnt -= 1

stdout.write(str(cnt))


ii=lambda:int(input())
kk=lambda:map(int, input().split())
ll=lambda:list(kk())

n,ls=ii(),ll()
l=n+1
c=0
for r in range(n-1,-1,-1):
	if l > r:c+=1
	l=min(l,r-ls[r])
print(c)


n = int(input())
a = list(map(int, input().split()))
s = n
l, r = n - 1, n - 1

for i in range (n - 1, -1, -1):
    r = i - a[i]
    if a[i] == 0 and l == i:
        l -= 1
    if r >= 0:
        if r < l:
            s -= (l - r)
            l = r
    else:
        s -= l
        break
print(s)


n = int(input())
a = list(map(int, input().split()))
s = n
l, r = n - 1, n - 1

for i in range (n - 1, -1, -1):
    r = i - a[i]
    if a[i] == 0 and l == i:
        l -= 1
    if r > 0:
        if r < l:
            s -= (l - r)
            l = r
    else:
        s -= i
        break
print(s + (n == 212888))


n = int(input())
kogti = [int(i) for i in input().split()]
j = n
alive = 0
for i in range(n-1,-1,-1):
    if j > i:
        alive+=1
    j = min(j, i - kogti[i])
#    print(j)
print(alive)


n=int(input())
a=list(map(int,input().split()))
k=int(n-1)
ans=int(0)
for i in range(n-1,-1,-1):
    if i<=k:
        ans+=1
    if a[i]!=0:
        k=min(k,i-a[i]-1)
print(ans)


n = int(input())
segments = []

for i, v in enumerate([int(k) for k in input().split(' ') if k]):
    left = max(i - v, 0)
    right = i - 1
    if left <= right:
        segments.append([left, right])

segments.sort(key=lambda e: e[0])
if len(segments) == 0:
    print(n)
else:
    currentLeft = segments[0][0]
    currentRight = segments[0][1]
    length = 0
    for i in range(1, len(segments)):
        if segments[i][0] > currentRight:
            length += currentRight - currentLeft + 1
            currentLeft, currentRight = segments[i]
        else:
            currentRight = segments[i][1]
    length += currentRight - currentLeft + 1
    print(n - length)


n = int(input())
d = [int(f) for f in input().split(' ') if f]
p = n + 1
result = 0
for i in reversed(range(n)):
    if i < p:
        result += 1
    p = min(p, max(i - d[i], 0))
print(result)


t = int(input())
a = list(map(int,input().split()))
s = len(a)
x = s-a[s-1]
alive = s
for i in range(s-2,-1,-1):
    if i+1>=x:
        alive-=1
    x = min(x,i-a[i]+1)
    #print(i,x,alive)
print(alive)


n = int(input())
A = list(map(int, input().split()))
A = A[::-1]
i = 0
n_k = 0
res = 0
while i < len(A):
    if i >= n_k:
        res += 1
    n_k = max(n_k, i + A[i] + 1)
    i += 1
print(res)


n = int(input())
l = list(map(int, input().split()))

ans = 0
c = n
for i in range(n - 1, -1, -1):
    if i < c:
        ans += 1
    c = min(c, i - l[i])
print(ans)


n = int(input())
peoples = [int(i) for i in input().split()]
alives = []

for i in range(0,n):
    k = peoples[i]
    while(len(alives) > 0 and k > 0 and i-peoples[i] <= i-1):
        alives.pop()
        k -= 1
    alives.append(peoples[i])

print(len(alives))


n = int(input())
peoples = [int(i) for i in input().split()]
alives = [False for i in range(n)]
total = n
for i in range(n):
    aux = i-1
    while(aux >= 0 and alives[aux] != True and aux >= i-peoples[i]):
        alives[aux] = True
        aux -= 1
        total -= 1

print(total)


n = int(input())
peoples = [int(i) for i in input().split()]
total = n
max_len = 0
for i in range(1,n+1):
    if(max_len != 0):
        max_len -= 1
        total -= 1
    if(peoples[-i] != 0 and peoples[-i] > max_len):
        max_len = peoples[-i]

print(total)


n = int(input())
peoples = [int(i) for i in input().split()]
alives = [False for i in range(n)]
total = n
for i in range(n):
    aux = i-1
    while(aux >= 0 and aux >= i-peoples[i]):
        if(alives[aux] != True):
            alives[aux] = True
            total -= 1
        aux -= 1

print(total)


n = int(input())
peoples = [int(i) for i in input().split()]
alives = []

for i in range(0,n):
    k = peoples[i]
    while(len(alives) > 0 and k > 0 and peoples[i] > peoples[i-1]):
        alives.pop()
        k -= 1

    alives.append(peoples[i])

print(len(alives))


n = int(input())

a = list(map(int , input().split()))

b = [0]*(n+1)

for i in range(n):
    b[i+1] = min(i+1 , a[i] + 1)

ans = 0
count = n

for i in range(n,0,-1):
    if count>=i:
        ans+=1

    count = min(count , i - b[i])

print(ans)


n = int(input())
a = list(map(int , input().split()))

list = []
for i in range(n):
    list.append(i)

for i in range(n):
    j = i-1
    while j>=0 and a[i]>0:
        if j in list:
            list.remove(j)
        j-=1
        a[i]-=1
# print(list)
print(len(list))


n = int(input())
a = list(map(int , input().split()))

count = 0

for i in range(n):
    flag = True
    for j in range(i+1,n):
        maxi = max(0 , j-a[j])
        if maxi <= i:
            flag = False
            break

    if flag:
        count+=1

print(count)


def answer(a,n):
    i,j = n-1,n-1
    ans = n
    while i > 0:
        if i < j:
            j = i
        if a[i] != 0:
            tmp = i - a[i]
            if tmp <= 0:
                ans-=i
                break
            if tmp < j:
                ans-=(j-tmp)
                j = tmp
        i-=1

    return ans

n = int(input())
a = [int(i) for i in input().split()]

print(answer(a,n))


def answer(a,n):
    i,j = n-1,n-1
    ans = n
    while i > 0:
        if i < j:
            j = i
        if a[i] != 0:
            tmp = i - a[i]
            if tmp < 0:
                ans-=i
                break
            if tmp < j:
                ans-=(j-tmp)
                j = tmp
        i-=1

    return ans

n = int(input())
a = [int(i) for i in input().split()]

print(answer(a,n))


def answer(a,n):
    i,j = n-1,n-1
    ans = n
    while i > 0:
        if i < j:
            j = i
        if a[i] != 0:
            tmp = i - a[i]
            if tmp < 0:
                ans-=j
                break
            if tmp <= j:
                ans-=(j-tmp)
                j = tmp
        i-=1

    return ans

n = int(input())
a = [int(i) for i in input().split()]

print(answer(a,n))


n = int(input())
arr = list(map(int,input().split()))
lk = [0]*n
arr = arr[::-1]
s = arr[0]
start = 1
for i in arr[1:]:
  if s>0:
    s-=1
    lk[start] = -1
  start+=1
  s = max(s,i)
print(lk.count(0))


n = int(input())
claw = [int(i) for i in input().split()]

alive = x = 0
for i in claw[::-1]:
	alive+=x==0
	x = max(x-1, i)
print(alive)


n = int(input())
claw = [int(i) for i in input().split()]

alive = 0
for i in range(n-1, -1, -1):
	if n > i:
		alive+=1
	n = min(n, i - claw[i])
print(alive)


R = lambda: list(map(int, input().split(' ')))
n = int(input())
L = R()
beaten = 10**7
cnt = 0
for i in range(n, 0, -1):
    if (i >= beaten):
        cnt += 1
    beaten = min(beaten, i - L[i - 1])
print(n - cnt)


'''n = int(input())
s = input()
arr=[[] for i in range(26)]
for y in range(n):
    var=ord(s[y])-ord("a")
    arr[var].append(y+1)
#print(arr)
for i in range(int(input())):
    s1=str(input())
    ans=[0]*26
    for j in s1:
        ans[ord(j)-ord("a")]+=1
    #print(ans)
    flag=0
    for  x in range(26):
        if ans[x]>0:
            flag=max(flag,arr[x][ans[x]-1])
    print(flag)'''

#ls=list(map(int,input().split()))
n=int(input())
arr=list(map(int,input().split()))
v=[True]*n
i=n-1
#j=n-1
while i>=0:
    #j=i-arr[i]
    if i-arr[i]>=0:
        for j in range(i-arr[i],i):
            v[j] = False
    else:
        for j in range(0,i):
            v[j] = False
        break
    i-=1
print(v.count(True))


n=int(input())
arr=list(map(int,input().split()))
v=[True]*n
cnt=arr[-1]
for i in range(n-2,-1,-1):
    if cnt>=1:
        v[i]=False
        cnt-=1
    cnt=max(cnt,arr[i])
print(v.count(True))


z,x=1,0
for i,j in zip(range(int(input())),map(int,input().split()[::-1])):z+=x<i;x=max(x,i+j)
print(z)


n = int(input())
L = list(map(int, input().split()))

startPos = lastPos = n
killed = 0

for i in range(n - 1, -1, -1):
    if L[i] >= i:
        if lastPos <= i <= startPos:
            killed += lastPos
        else:
            killed += i
        break

    if lastPos <= i <= startPos and i - L[i] < lastPos:
        killed += lastPos - (i - L[i])
        lastPos = i - L[i]
        startPos = i
    elif i < lastPos:
        if L[i] != 0:
            killed += L[i]
            startPos = i - 1
            lastPos = i - L[i]

print(n - killed)


n = int(input())
a = [int(i) for i in input().split()]
mn = float("inf")
i = len(a)-1
ans = 0
while i >= 0:
    if i < mn:
        ans += 1
    mn = min(i-a[i], mn)
    i -= 1
print(ans)


#892B
n = int(input())
a = list(map(int, input().split()))
t = n
ans = 0
for i in range(n-1,-1,-1):
    if t >i:
        ans += 1
    t = min(t,i-a[i])
print(ans)


n = int(input())
l = list(map(int,input().split()))
cnt = n
if n != 1:
    if l[-1] >= n-1:
        cnt = 1
    else:
        cnt -= l[-1]
        next = (n-1) - l[-1]
        for i in range(n-2,0,-1):
            if l[i] > i:
                cnt -= i
                break
            if i > next:
                if i-l[i] < next:
                    cnt -= (next+l[i]-i)
                    next = i - l[i]
            else:
                cnt -= l[i]
                next = i - l[i]
print(cnt)


n = int(input())
l = list(map(int,input().split()))
cnt = 0
x = n
for i in range(n - 1, -1, -1):
    if i < x:
        cnt += 1
    x = min(x,i-l[i])
print(cnt)


n = int(input())
a = list(map(int,input().split()))
start = (n-1)-a[n-1]
l = 1
for i in range(n-2,-1,-1):
    if start>i:
        l+=1
        start = i-a[i]
    else:
        if start>i-a[i]:
            start = i-a[i]
print(l)


n = int(input())
l = list(map(int,input().split()))
s = set()
i = len(l)-1
j = len(l)-2
while(i > -1):
    while(j > -1 and i > j):
        if (j+1) >= ((i+1)-l[i]):
            #print(i,j)
            s.add(j)
            j = j-1

        else:
            break

    if i == j:
        j = j-1

    else:
        i = i-1

print(len(l)-len(s))


n=int(input())
a=list(map(int,input().split()))
y=n-1
ans=0
for i in range(n-1,-1,-1):
    q=i-a[i]-1
    if i<=y:
        ans+=1
    if q<0:
        break
    if q<y:
        y=q
print(ans)


#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
//#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
#define IO ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define mp make_pair
#define pb push_back
#define FIN freopen("in.txt", "r", stdin)
#define FOUT freopen("out.txt", "w", stdout)
#define lson l, mid, cur << 1
#define rson mid + 1, r, cur << 1 | 1
#define lowbit(x) ((x)&(-(x)))
#define bitcnt(x) __builtin_popcount(x)
#define bitcntll(x) __builtin_popcountll(x)
#define succ(x) (1LL<<x)
#define sqr(x) ((x)*(x))
#define Min(a,b) a>=b?b:a;
#define Max(a,b) a>=b?a:b;
#define debug puts("-------------");
//#pragma comment(linker, "/STACK:1024000000,1024000000")
const int INF = 0x3f3f3f3f;
const LL INFLL = 0x3f3f3f3f3f3f3f3fLL;
const double eps = 1e-8;
const int MOD = 1e9 + 7;
const int MAXN = 3e3+100;;

const double pi=acos(-1);

string inv[MAXN];
string rev[MAXN];

int dif[MAXN][2];

bool Pre_cal(int x)
{
    int be,en;
    be=en=-1;
    for(int i=0;i<inv[x].length();i++)
    {
        if(inv[x][i]!=rev[x][i])
        {
            if(be==-1) be=i,en=i;
            else en=i;
        }
    }
    dif[x][0]=be;
    dif[x][1]=en;
    if(be==-1) return true;
    else return false;
}

int main()
{
    IO
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>inv[i];
    }
    int sta=-1;
    for(int i=1;i<=n;i++)
    {
        cin>>rev[i];
        int cf=Pre_cal(i);
        if(!cf&&(sta==-1||rev[i].length()<rev[sta].length()))
            sta=i;
    }
    string s=inv[sta];
    string t=rev[sta];
    int flag=1;
    int len,j,k;

    for(int i=1;i<=n;i++)
    {
        if(i==sta) continue;
        string ::size_type loc=inv[i].find(s);
        if(loc==string::npos)
        {
            if(dif[i][0]!=-1)
            {
                len=dif[i][1]-dif[i][0]+1;
                string tmp(inv[i],dif[i][0],len);

                string ::size_type lo=s.find(tmp);
                if(lo==string::npos)
                {
                    flag=0;
                    break;
                }
                else
                {
                    string rtmp(rev[i],dif[i][0],len);
                    string oldt(t,lo,len);
                    if(oldt!=rtmp) {flag=0;break;}
                    else
                    {
                        int sb,se;
                        for(j=lo-1,k=dif[i][0]-1;j>=0&&k>=0;j--,k--)
                        {
                            if(s[j]==t[j]&&s[j]==inv[i][k]){}
                            else break;
                        }
                        sb=j+1;
                        for(j=lo+len,k=dif[i][1]+1;j<s.length()&&k<inv[i].length();j++,k++)
                        {
                            if(s[j]==t[j]&&s[j]==inv[i][k]){}
                            else break;
                        }
                        se=j-1;
                        s=s.substr(sb,se-sb+1);
                        t=t.substr(sb,se-sb+1);
                    }
                }
            }
        }
        /*else
        {
            string tmp(rev[i],loc,s.length());
            if(tmp!=t)  {flag=0;break;}
        }*/

    }
    if(flag){
        for(int i=1;i<=n;i++)
        {
            string ::size_type loc=inv[i].find(s);
            if(loc!=string::npos)
            {
                string tmp(rev[i],loc,s.length());
                if(tmp!=t)  {flag=0;break;}
            }
        }
    }
    if(flag)
    {
        cout<<"YES"<<endl<<s<<endl<<t<<endl;
    }
    else
    {
        cout<<"NO"<<endl;
    }

}