Cod sursa(job #1990538)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 12 iunie 2017 14:50:29
Problema Cuburi2 Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.96 kb
#include <fstream>

using namespace std;

ofstream fout ("cuburi2.out");

class InputReader {
	public:
        InputReader() {}
        InputReader(const char *name) {
            fin = fopen(name, "r");
			buffpos = Size - 1;
        }
        inline InputReader &operator >>(int &n) {
			char ch = nextpos();
            while((ch < '0' || ch > '9') && ch != '-') {
                ch = nextpos();
            }

            n = 0;
            while('0' <= ch && ch <= '9') {
                n = n * 10 + ch - '0';
                ch = nextpos();
            }
            return *this;
        }
    private:
        FILE *fin;
        static const int Size = 1 << 17;
        int buffpos;
        char buff[Size];

        inline char nextpos() {
            ++ buffpos;
            if(buffpos == Size) {
                buffpos = 0;
                fread(buff, Size, 1, fin);
            }
			return buff[ buffpos ];
        }
} fin ("cuburi2.in");

typedef long long i64;

const int nmax = 25e4 + 5;

int n, x, y;
int v[nmax + 1];
i64 s[nmax + 1], sp[nmax + 1];

inline i64 check (int pos) {
    i64 st, dr;
    st = (sp[pos - 1] - sp[x - 1]) * pos - (s[pos - 1] - s[x - 1]);
    dr = (s[ y ] - s[ pos ]) - (sp[ y ] - sp[ pos ]) * pos;
    return st + dr;
}

int main() {
    int m;
    fin >> n >> m;

    for (int i = 1; i <= n; ++ i) {
        fin >> v[ i ];

        sp[ i ] = sp[i - 1] + 1LL * v[ i ];
        s[ i ] = s[i - 1] + 1LL * i * v[ i ];
    }

    sp[n + 1] = sp[ n ];
    s[n + 1] = s[ n ];

    for (int i = 1; i <= m; ++ i) {
        fin >> x >> y;

        int n2;
        for (n2 = 1; (n2 << 1) <= y - x + 1; n2 <<= 1) {
        }

        int ans = x;
        for (int step = n2; step > 0; step >>= 1) {
            if (ans + step + 1 <= y && check(ans + step) > check(ans + step + 1)) {
                ans += step;
            }
        }

        if (ans + 1 <= y && check( ans ) > check(ans + 1)) ++ ans;

        fout << ans << " " << check(ans) << "\n";
    }

    return 0;
}