Cod sursa(job #1053224)

Utilizator Lucian-GeorgeFMI Popa Lucian George Lucian-George Data 12 decembrie 2013 15:49:16
Problema Deque Scor 25
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include<iostream>
#include<fstream>
using namespace std;

typedef struct heap
{
	int ord,val;
} HE;
HE h[2000000];
int p[2000000],nr=0; //p[i]=pozitia in heap a al i-lea element introdus

void insert(int x, int ord)
{
	int poz;
	h[++nr].val=x;
	h[nr].ord=ord;
	p[ord]=nr;
	poz=nr;
	while (h[poz].val<h[poz/2].val && poz/2>=1)
	{
		int t=p[h[poz].ord];
		HE aux=h[poz];
		p[h[poz].ord]=p[h[poz/2].ord];
		h[poz]=h[poz/2];
		p[h[poz/2].ord]=t;
		h[poz/2]=aux;
		poz=poz/2;
	}
}

void sterge(int ord)
{
	int po=p[ord],poz;
	poz=po;
	h[po]=h[nr--];
	p[h[po].ord]=po;
	while ((h[po].val>h[po*2].val && po*2<=nr) || (h[po].val>h[po*2+1].val && po*2+1<=nr))
		if (po*2<=nr && po*2+1<=nr && h[po*2+1].val<h[po*2].val)
		{
			int t=p[h[po].ord];
			HE aux=h[po];
			p[h[po].ord]=p[h[po*2+1].ord];
			h[po]=h[po*2+1];
			p[h[po*2+1].ord]=t;
			h[po*2+1]=aux;
			po=po*2+1;
		}
		else
		{
			int t=p[h[po].ord];
			HE aux=h[po];
			p[h[po].ord]=p[h[po*2].ord];
			h[po]=h[po*2];
			p[h[po*2].ord]=t;
			h[po*2]=aux;
			po=po*2;
		}
	while (h[poz].val<h[poz/2].val && poz/2>=1)
	{
		int t=p[h[poz].ord];
		HE aux=h[poz];
		p[h[poz].ord]=p[h[poz/2].ord];
		h[poz]=h[poz/2];
		p[h[poz/2].ord]=t;
		h[poz/2]=aux;
		poz=poz/2;
	}
}

			
	
int main()
{
	int i,n,in=0,x,a,k,s=0;
	ifstream f("deque.in");
	ofstream g("deque.out");
	f>>n>>k;
	for (i=1; i<k; i++)
	{
		f>>a;
		++in;
		insert(a,in);
	}
	for (i=k; i<=n; i++)
	{
		f>>a;
		++in;
		insert(a,in);
		while (h[1].ord<i-k+1) sterge(h[1].ord);
		s=s+h[1].val;
	}
	g<<s;
	return 0;
}