Cod sursa(job #1053963)

Utilizator hellol30FMI Macovei Daniel hellol30 Data 13 decembrie 2013 02:09:58
Problema Deque Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include<cstdio>
#include<algorithm>
#define NM 5000010 
#define DIM 10000
using namespace std;

int n,k,nmax;
long long s;
pair< int,int > heap[NM],aux;

char buff[DIM];
int poz=0;
 
void cit(int &numar)
{
     numar = 0;
     char semn='+';     
     while (buff[poz] < '0' || buff[poz] > '9')
     {     
          semn = buff[poz];
          if (++poz == DIM) 
               fread(buff,1,DIM,stdin),poz=0;
     }          
     while ('0'<=buff[poz] && buff[poz]<='9')
     {
          numar = numar*10 + buff[poz] - '0';
          if (++poz == DIM) 
               fread(buff,1,DIM,stdin),poz=0;               
     }     
     if (semn == '-')
          numar = -numar;
}
inline void coboara(int nod)
{
    while( nod*2+1<=nmax && ( heap[nod].first >= heap[nod*2].first || heap[nod].first >= heap[nod*2+1].first ) )
        if(heap[nod*2+1].first<heap[nod*2].first) 
		{
			swap(heap[nod],heap[nod*2+1]);
			nod=nod*2+1;
		}
		else 
		{
			swap(heap[nod],heap[nod*2]);
			nod=nod*2;
		}
    if(nod*2==nmax && heap[nod].first >= heap[nod*2].first)
        swap(heap[nod],heap[nod*2]);
}
int main()
{
    freopen("deque.in","rt",stdin);
    freopen("deque.out","wt",stdout);
    cit(n); cit(k);
	
    for(register int i=1;i<=n;++i)
    {
        for(cit(aux.first); nmax>0 && ( ( heap[1].second <= i-k ) || (heap[1].first >= aux.first) ) ; coboara(1))
			heap[1]=heap[nmax--];
		
		aux.second=i;
		for(heap[++nmax]=aux; nmax>1 && heap[nmax].first <= heap[nmax/2].first;nmax/=2)
			swap(heap[nmax],heap[nmax/2]);
        s+=(i>=k)*heap[1].first;
    }
    printf("%lld\n",s);
    return 0;
}