Cod sursa(job #980963)

Utilizator Mihai22eMihai Ionut Enache Mihai22e Data 6 august 2013 00:50:06
Problema Cuburi2 Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.58 kb
#include <fstream>
using namespace std;

const int MAX_N = 250002;
const long long int INF = 999999999999999999;

int N, M;
int v[MAX_N];
long long int st[MAX_N], dr[MAX_N], a[MAX_N], b[MAX_N];

int main() {
    ifstream f("cuburi2.in");
    ofstream g("cuburi2.out");

    f >> N >> M;
    for(int i = 1; i <= N; ++i) {
        f >> v[i];
        a[i] = v[i] + a[i-1], st[i] = st[i-1] + a[i-1];
    }

    for(int i = N; i; --i)
        b[i] = v[i] + b[i+1], dr[i] = dr[i+1] + b[i+1];
    while(M--) {
        int x, y, ind, alpha, l, r, pos;
        f >> x >> y;
        alpha = (y-x+1)/2, l = x, r = y;
        long long int BestCost, Cost1, Cost2;
        pos = (x+y)/2;
        BestCost = st[pos] - st[x] - a[x-1]*(pos-x) + dr[pos] - dr[y] - b[y+1]*(y-pos), ind = pos;
        while(alpha) {
            pos = (l+r)/2 - alpha;
            if(pos < x)
                Cost1 = INF;
            else Cost1 = st[pos] - st[x] - a[x-1]*(pos-x) + dr[pos] - dr[y] - b[y+1]*(y-pos);

            pos = (l+r)/2 + alpha;
            if(pos > y)
                Cost2 = INF;
            else Cost2 = st[pos] - st[x] - a[x-1]*(pos-x) + dr[pos] - dr[y] - b[y+1]*(y-pos);
            if(Cost1 < BestCost) {
                BestCost = Cost1, ind = (l+r)/2 - alpha;
                r = (l+r)/2 - alpha;
            }
            else if(Cost2 < BestCost) {
                BestCost = Cost2, ind = (l+r)/2 + alpha;
                l = (l+r)/2 + alpha;
            }
            else alpha /= 2;
        }

        g << ind << " " << BestCost << "\n";
    }

    return 0;
}