Pagini recente » Rating Time Limit Exceeded (mrvalentyn) | Cod sursa (job #1805343) | Cod sursa (job #28759) | Cod sursa (job #1703238) | Cod sursa (job #274244)
Cod sursa(job #274244)
#include<stdio.h>
#define INPUT "heapuri.in"
#define OUTPUT "heapuri.out"
#define NMAX 200001
#define INFI 2000000000
FILE *fin = fopen(INPUT, "r"), *fout = fopen(OUTPUT, "w");
long Heap[ NMAX ], PHeap[ NMAX ], PEnter[ NMAX ];
long PozH, PozN;
inline void twist(long &_A, long &_B)
{
_A = _A + _B;
_B = _A - _B;
_A = _A - _B;
}
void AddHeap(long _X)
{
++PozH;
++PozN;
long PCur = PozH;
Heap[ PozH ] = _X; ///Heapul sortat
PHeap[ PozN ] = PozH; ///Pozitia in heap a celui de-al i-lea element
PEnter[ PozH ] = PozN; ///Pozitia de intrare a elementului de pe pozitia i din heap
while( PCur / 2 > 0 && Heap[ PCur / 2 ] > Heap[ PCur ])
{
twist(Heap[ PCur / 2 ], Heap[ PCur ]);
twist(PEnter[ PCur / 2 ], PEnter[ PCur ]);
twist(PHeap[ PEnter[ PCur / 2] ], PHeap[ PEnter[ PCur ] ]);
PCur /= 2;
}
for(long i = 1; i <= PozH; ++i)
fprintf(stderr, "%ld ", Heap[ i ]);
fprintf(stderr, "\n");
}
void ExtractHeap(long _X)
{
Heap[ PHeap[ _X ] ] = Heap[ PozH ];
Heap[ PozH ] = INFI;
PEnter[ PHeap[ _X ] ] = PEnter[ PozH ];
PEnter[ PozH ] = -1;
PHeap[ PEnter[ PHeap[ _X ] ] ] = PHeap[ _X ];
--PozH;
long PCur = PHeap[ _X ];
PHeap[ _X ] = -1;
while(PCur * 2 <= PozH)
{
if(PCur * 2 + 1 <= PozH && Heap[ PCur * 2 + 1 ] < Heap[ PCur * 2 ])
{
twist(Heap[ PCur ], Heap[ PCur * 2 + 1]);
twist(PEnter[ PCur ], PEnter[ PCur * 2 + 1]);
twist(PHeap[ PEnter[ PCur ] ], PHeap[ PEnter[ PCur * 2 + 1 ] ]);
PCur = PCur * 2 + 1;
}
else
{
twist(Heap[ PCur ], Heap[ PCur * 2 ]);
twist(PEnter[ PCur ], PEnter[ PCur * 2 ]);
twist(PHeap[ PEnter[ PCur ] ], PHeap[ PEnter[ PCur *2 ] ] );
PCur = PCur * 2;
}
}
}
int main()
{
long N, X;
int Code;
PozH = 0;
PozN = 0;
fscanf(fin, "%ld", &N);
for(long i = 0; i < N; ++i)
{
fscanf(fin, "%d", &Code);
if(Code == 1)
{
fscanf(fin, "%ld", &X);
AddHeap(X);
}
else
if(Code == 2)
{
fscanf(fin, "%ld", &X);
ExtractHeap(X);
}
else
fprintf(fout, "%ld\n", Heap[ 1 ]);
}
fclose(fin);
fclose(fout);
return 0;
}