Cod sursa(job #993750)

Utilizator mitrutstrutMitrea Andrei Ionut mitrutstrut Data 4 septembrie 2013 13:19:20
Problema Cuburi2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.58 kb
#include <cstdio>
#include <cstring>
using namespace std;
  
const int MAX_N = 250002;
  
int N, M;
int v[MAX_N];
long long int st[MAX_N], dr[MAX_N], a[MAX_N], b[MAX_N];
char S[60];
  
int main() {
    FILE *f, *g;
    f = fopen("cuburi2.in", "r");
    g = fopen("cuburi2.out", "w");
  
    fscanf(f, "%d %d", &N, &M);
    for(int i = 1; i <= N; ++i) {
        fscanf(f, "%d", &v[i]);
        a[i] = v[i] + a[i-1], st[i] = st[i-1] + a[i-1];
    }
    fgets(S, 3, f);
  
    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 = -1, y = -1, ind = 0, l, r, m, len, temp;
        fgets(S, 50, f);
        len = strlen(S);
        for(int i = 0; i < len; ++i)
            if(S[i] >= '0' && S[i] <= '9') {
                temp = 0;
                while(S[i] >= '0' && S[i] <= '9')
                    temp = temp*10 + S[i] - '0', ++i;
                if(x == -1)
                    x = temp;
                else y = temp;
            }
        l = x, r = y;
        long long int BestCost, Cost1, Cost2;
        while(l <= r) {
            m = (l+r)/2;
            if(l == y && r == y) {
                ind = y;
                break;
            }
            Cost1 = st[m] + dr[m] - b[y+1];
            Cost2 = st[m+1] - a[x-1] + dr[m+1];
            if(Cost1 <= Cost2)
                ind = m, r = m-1;
            else l = m+1;
        }
        BestCost = st[ind] - st[x] - a[x-1]*(ind-x) + dr[ind] - dr[y] - b[y+1]*(y-ind);
  
        fprintf(g, "%d %lld\n", ind, BestCost);
    }
  
    return 0;
}