In the array, for all elements, find the next element larger than the current element
The meaning is, eg. Array is 3 1 2 5 4 6 7
So the result we need to get is 5 2 5 6 6 7-1
Here's how to fix it:
- Violent match: O (n ^ 2) efficiency matches all elements in the past and is very inefficient
- I've been prompted to think of an O (NLG n) Efficiency algorithm
Only need to scan the array once, we use a priority_queue to get the current smallest element
The data structures stored by Prority_queue are:
struct SC { int key, flag; BOOL operator < (const SC & a) const {return A.key < key;}};
Key denotes the value of the element, and flag indicates the subscript, which is useful when assigning a value
Algorithm ideas:
Traversal once, if the current queue is empty, then push
Otherwise, if the minimum element of the first team is less than a[i]
Then assigning a value in the answer array gives the next element larger than the current element
If the queue is empty, break
My Source code:
#include <iostream>#include<cstring>#include<stack>#include<string>#include<ctime>#include<queue>#include<algorithm>using namespacestd;Const intMAXN = +;intA[MAXN], B[MAXN];structSC {intkey, Flag; BOOL operator< (ConstSC & A)Const { returnA.key <key;}};intMain () {intI, J, K, U, V, n; memset (b,-1,sizeof(b)); CIN>>N; for(i =0; I < n; ++i) Cin >>A[i]; Priority_queue<sc>que; for(i =0; I < n; ++i) {if(Que.empty ()) {SC temp; Temp.key= A[i], Temp.flag =i; Que.push (temp); Continue; } for (;;) { if(Que.empty ()) Break;//if pop to empty break; if(Que.top (). Key <A[i]) {b[que.top (). Flag]=A[i]; Que.pop (); } Else Break; } SC temp; Temp.key=A[i]; Temp.flag=i; Que.push (temp); } for(i =0; I < n; ++i) {cout<< A[i] <<' '; } cout<<Endl; for(i =0; I < n; ++i) {cout<< B[i] <<' '; } cout<<Endl; return 0;}
"Fun algorithm Problem" in the array, for all elements, find the next element larger than the current element