题目:Array A has N positive integers,for each A[i] (0<=i<N, indicating the i-th integer in the array A), it fits in a 32-bit signed integer ),find the closest number less than A[i] (if the distance is the same,we prefer the left one).
- 样例输入:
-
3 3 2 1 3 3 2 3 1 4 5 7 3 6
- 样例输出:
-
1 0 1 1 2 0 3 5 0 3
思路:
1.从左往右遍历,维护一个索引结构的记录数组R[],和一个索引结构升序栈S[],依次压入A[i],同时A[i]左侧的closet number记录R[]为栈顶索引元素,
2.从右往左遍历,可以继续用1中的栈S[],也可以重新做另一个升序栈SS[],然后按照1的过程从右往左遍历,比较R[]和S[];
下面是我提交的已经Accepted的代码:
1 #include <iostream> 2 using std::cout; 3 using std::cin; 4 using std::endl; 5 const int NUM=1000001; 6 int AA[NUM]={0}; 7 struct Rec 8 { 9 int value; 10 int idx; 11 }R[NUM],S[NUM]; 12 int main() 13 { 14 int n; 15 int num; 16 //设置栈0元素。 17 int top=0; 18 S[top].value=0; 19 S[top].idx =0; 20 cin>>n; 21 for(int i=0;i<n;i++) 22 { 23 cin>>num; 24 for(int i=1;i<=num;i++) 25 { 26 cin>>AA[i]; 27 R[i].value=0; 28 R[i].idx=0; 29 } 30 top=0; 31 for(int i=1;i<=num;i++) 32 { 33 //出栈 34 while( AA[i]<=S[top].value ) 35 top--; 36 R[i] =S[top]; 37 //入栈 38 top++; 39 S[top].value=AA[i]; 40 S[top].idx=i; 41 } 42 top=0; 43 for(int i=num;i>0;i--) 44 { 45 //出栈 46 while( AA[i]<=S[top].value ) 47 top--; 48 if( (top>0)&&((R[i].value ==0)||((i-R[i].idx)>(S[top].idx-i)))) 49 R[i]=S[top]; 50 //入栈 51 top++; 52 S[top].value=AA[i]; 53 S[top].idx=i; 54 } 55 for(int i=1; i<num;i++) 56 cout<<R[i].value << " "; 57 cout<<R[num].value; 58 cout<<endl; 59 }//for 60 return 0; 61 }