Pagini recente » Cod sursa (job #1154068) | Cod sursa (job #304274) | Cod sursa (job #2686353) | Cod sursa (job #27476) | Cod sursa (job #749198)
Cod sursa(job #749198)
#include <fstream>
#include <iostream>
using namespace std;
typedef struct heapelem{
int key,index;
}heapelem;
heapelem heap[500000];
int secv[500000];
int baza[500000];
int pox[500000];
void heapify(int k,int n)
{
while (k<n){
int l = 2*k+1;
int r = 2*k+2;
int max = k;
if (l<n && heap[l].key<heap[k].key) max = l;
if (r<n && heap[r].key<heap[max].key) max= r;
if (max!=k)
{
int aux = heap[k].key;
heap[k].key=heap[max].key;
heap[max].key=aux;
aux = heap[k].index;
heap[k].index=heap[max].index;
heap[max].index=aux;
pox[heap[k].index] = k;
pox[heap[max].index]=max;
k=max;
}
else return;
}
}
void heapifyup(int k)
{
while (k>0 && heap[k].key<heap[(k-1)/2].key)
{
int max = (k-1)/2;
int aux = heap[k].key;
heap[k].key=heap[max].key;
heap[max].key=aux;
aux = heap[k].index;
heap[k].index=heap[max].index;
heap[max].index=aux;
pox[heap[k].index] = k;
pox[heap[max].index]=max;
k = (k-1)/2;
}
}
void deleteelem(int poz,int &n)
{
int k=poz;
int max = n-1;
int aux = heap[k].key;
heap[k].key=heap[max].key;
heap[max].key=aux;
aux = heap[k].index;
heap[k].index=heap[max].index;
heap[max].index=aux;
pox[heap[k].index] = k;
pox[heap[max].index]=max;
n--;
heapify(0,n);
}
heapelem* extractmin(int &n)
{
int k=0;
int max = (n-1);
int aux = heap[k].key;
heap[k].key=heap[max].key;
heap[max].key=aux;
aux = heap[k].index;
heap[k].index=heap[max].index;
heap[max].index=aux;
pox[heap[k].index] = k;
pox[heap[max].index]=max;
n--;
heapify(0,n);
return &heap[n];
}
int main()
{
ifstream f("secventa.in",ios::in);
int n,k;
f>>n>>k;
for (int i=0;i<n;i++)
f>>secv[i];
int heapsize = 0;
f.close();
if (n==k)
{
int maxi = secv[0];
for (int i=1;i<n;i++)
if (secv[i]<maxi) maxi =secv[i];
ofstream g("secventa.out",ios::out);
g<<"1"<<" "<<n<<" "<<maxi<<endl;
g.close();
return 0;
}
for (int i=0;i<k;i++)
{
heap[heapsize].key=secv[i];
heap[heapsize].index = i;
pox[i] = heapsize;
heapifyup(heapsize);
heapsize++;
baza[i]=heap[0].key;
}
int maxim = k-1;
for (int i=k;i<n;i++)
{
deleteelem(pox[i-k],heapsize);
heap[heapsize].key = secv[i];
heap[heapsize].index = i;
pox[i] = heapsize;
heapifyup(heapsize);
heapsize++;
baza[i] = heap[0].key;
if (baza[i]>baza[maxim])
maxim=i;
}
ofstream g("secventa.out",ios::out);
g<<maxim-k+2<<" "<<maxim+1<<" "<<baza[maxim]<<endl;
g.close();
return 0;
}