Cod sursa(job #1053256)

Utilizator Lucian-GeorgeFMI Popa Lucian George Lucian-George Data 12 decembrie 2013 16:32:51
Problema Deque Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;

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

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

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

			
	
int main()
{
	int i,n,in=0,x,a,k;
	long long s=0;
	FILE *f,*g;
	f=fopen("deque.in","r");
	g=fopen("deque.out","w");
	fscanf(f,"%d",&n);
	fscanf(f,"%d",&k);
	for (i=1; i<k; i++)
	{
		
		fscanf(f,"%d",&a);
		++in;
		insert(a,in);
	}
	for (i=k; i<=n; i++)
	{
		
		fscanf(f,"%d",&a);
		++in;
		insert(a,in);
		while (h[1].ord<i-k+1) sterge(h[1].ord);
		s+=h[1].val;
	}
	fprintf(g,"%lld",s);
	return 0;
}