Cod sursa(job #1052646)

Utilizator BuseSorinFMI Buse Sorin-Marian BuseSorin Data 11 decembrie 2013 17:20:58
Problema Deque Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include<iostream>
#include<fstream>
using namespace std;

int heap[5000000];
int lheap;
int V[5000000];

void coboara(int poz){
	if(poz*2>lheap)return;
	int poz1=poz*2;
	if(poz*2+1<=lheap&&heap[poz*2+1]<heap[poz*2]){
		poz1++;
	}
	if(heap[poz1]<heap[poz]){
		swap(heap[poz],heap[poz1]);
		coboara(poz1);
	}
}
void elimina_min(){
	heap[1]=heap[lheap--];
	coboara(1);
}

void urca(int poz){
	while(poz>1 && heap[poz]<heap[poz/2]){
		swap(heap[poz],heap[poz/2]);
		poz/=2;
	}
}
void insert(int val){
	heap[++lheap]=val;
	urca(lheap);
}

void sterge(int poz){
	heap[poz]=heap[lheap];
	lheap--;
	coboara(poz);
	urca(poz);
}

int main(){
	ifstream f("deque.in");
	ofstream o("deque.out");
	int n=0;
	f>>n;
	int k=0;
	f>>k;
	lheap=0;
	long long s=0;
	int m=1;
	for(int i=1;i<=n;i++){
		int val=0;
		f>>val;
		V[i]=val;
		insert(val);
		if(i>k-1){
			s+=heap[1];
			for(int j=1;j<=lheap;j++){
				if(heap[j]==V[m]){
					sterge(j);
					break;
				}
			}
			m++;
		}
	}
	o<<s;
	return 0;
}