Cod sursa(job #3303476)

Utilizator Andrei-Dani-10Pisla Andrei Daniel Andrei-Dani-10 Data 15 iulie 2025 20:08:06
Problema Cuburi2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.79 kb
#include <fstream>

using namespace std;

ifstream in("cuburi2.in");
ofstream out("cuburi2.out");

const int nmax = 250000;
int n, a[nmax + 2], nrq, lf, rg;

int64_t sp[nmax + 2];
int64_t costtlf[nmax + 2];
int64_t costtrg[nmax + 2];

int64_t target, bestt;

int64_t getlfcost(int st, int dr, int pos){
    int64_t leftt = costtlf[pos - 1] - costtlf[st - 1];
    leftt -= 1ll * (n - pos + 1) * (sp[pos - 1] - sp[st - 1]);

    return leftt;
}

int64_t getrgcost(int st, int dr, int pos){

    int64_t rightt = costtrg[dr] - costtrg[pos];
    rightt -= 1ll * pos * (sp[dr] - sp[pos]);

    return rightt;
}

int64_t getcostt(int st, int dr, int pos){
    return getlfcost(st, dr, pos) + getrgcost(st, dr, pos);
}

int main(){

    in>>n>>nrq;
    for(int i = 1; i <= n; i++)
        in>>a[i], sp[i] = sp[i - 1] + a[i];

    for(int i = 1; i <= n; i++){
        costtlf[i] = costtlf[i - 1] + 1ll * (n - i + 1) * a[i];
        costtrg[i] = costtrg[i - 1] + 1ll * i * a[i];
    }

    for(int it = 1; it <= nrq; it++){
        in>>lf>>rg; bestt = (1ll << 60);

        ///Cost min -> lfcost == rgcost

        target = sp[rg] - sp[lf - 1];
        int st = lf, dr = rg, mij, pos = lf;

        for(; st <= dr; ){
            mij = (st + dr) >> 1;

            if(2ll * (sp[mij] - sp[lf - 1]) <= target){
                st = mij + 1; pos = mij;
            }else{ dr = mij - 1; }
        }

        bestt = (1ll << 60); target = -1;
        for(int i = max(lf, pos - 5); i <= min(rg, pos + 5); i++){
            if(bestt > getcostt(lf, rg, i)){
                bestt = getcostt(lf, rg, i);
                target = i;
            }
        }

        ///out<<target<<" "<<bestt<<"\n";
        out<<pos<<" "<<getcostt(lf, rg, pos)<<"\n";
    }

    return 0;
}