• 九度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 }
    **************************************************************
    我喜欢程序员,他们单纯、固执、容易体会到成就感;面对困难,能够不休不眠;面对压力,能够迎接挑战。他们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想,用智慧把属于自己的事业开创。其实我是一个程序员
    [=.=]
  • 相关阅读:
    Linq之旅:Linq入门详解(Linq to Objects)【转】
    Shadow Map 原理和改进 【转】
    OSG 中文解决方案 【转】
    shadow mapping实现动态shadow实现记录 【转】
    RenderMonkey 练习 第六天 【OpenGL Water 水效】
    glsl水包含倒影的实现(rtt) 【转】
    Docker镜像仓库Harbor之搭建及配置
    docker登录没有配置https的harbor镜像仓库
    Git 清除远端已删除的分支
    单节点k8s的一个小例子 webapp+mysql
  • 原文地址:https://www.cnblogs.com/kevinGaoblog/p/2520851.html
Copyright © 2020-2023  润新知