Cod sursa(job #2676947)

Utilizator teodorescunicolasteodorescu nicolas alexandru teodorescunicolas Data 25 noiembrie 2020 15:23:36
Problema Deque Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <stdio.h>
#define NMAXX 5000000

FILE *fin, *fout;
int deque[NMAXX], poz[NMAXX];

int readInt() {
    int ch, res = 0, semn = 1;
    while ( isspace( ch = fgetc( fin ) ) );
    if ( ch == '-' ) {
        semn = -1;
        ch = fgetc( fin );
    }
    do {
        res = 10 * res + ch - '0';
    } while ( isdigit( ch = fgetc( fin ) ) );
    return semn * res;
}

int main()
{
    int n, k, i, start, end, a;
    long long s;
    fin = fopen( "deque.in", "r" );
    fout = fopen( "deque.out", "w" );
    n = readInt();
    k = readInt();
    start = end = 0;
    for ( i = 0; i < k; i++ ) {
        a= readInt();
        while ( start < end && a < deque[end - 1] ) {
            end--;
        }
        deque[end] = a;
        poz[end] = i;
        end++;
    }
    s = 0LL;
    s += deque[start];
    for ( i = k; i < n; i++ ) {
        fscanf( fin, "%d", &a );
        while ( start < end && a < deque[end - 1] ) {
            end--;
        }
        deque[end] = a;
        poz[end] = i;
        end++;
        if ( poz[start] == i - k ) {
            start++;
        }
        s += deque[start];
    }
    fprintf( fout, "%lld", s );
    fclose( fin );
    fclose( fout );
    return 0;
}