|
|
вернуться в форумWhy Time Limit? complexity (n-m)*log(m) Idea: Using pointer connected heap and queue. Heap for maximum element. Queue to find element what needs to be extracted from heap. #include <fstream.h> ifstream fin("magnetic.dat"); //#define fin cin const int max=14001; short m, value[max], queue[max], heap[max+1], s,c,a; void heap_swap(short a, short b) { short x; x=heap[a]; heap[a]=heap[b]; heap[b]=x; x=queue[heap[a]]; queue[heap[a]]=queue[heap[b]]; queue[heap[b]]=x; } void push() { short e=(s+c)%max; value[e]=a; queue[e]=++c; heap[c]=e; short k=c; while(k>1 && value[heap[k>>1]]<value[heap[k]]) { heap_swap(k>>1,k); k=k>>1; } } void pop() { cout << value[heap[1]] << endl; short k=queue[s]; s++; s%=max; heap_swap(k,c--); while(k>1 && value[heap[k>>1]]<value[heap[k]]) { heap_swap(k>>1,k); k=k>>1; } short l=k<<1, m; while(l<=c) { m=k; if(value[heap[l]]>value[heap[m]]) m=l; if(l+1<=c && value[heap[l+1]]>value[heap[m]]) m=l+1; if(m==k) break; heap_swap(m,k); k=m; l=k<<1; } } void main() { fin >> m; for(int i=0; i<m; i++) {fin >> a; push();} while(1) { pop(); fin >> a; if(a==-1) break; push(); } } |
|
|