九度OnLine Judge 题目1422:Closest Number

题目: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 }

转载于:https://www.cnblogs.com/kevinGaoblog/archive/2012/05/28/2520851.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值