NOJ [1175] Dress, Left Dress!

本文介绍了一种针对士兵队列的高效算法,该算法通过一次遍历即可确定每个士兵左侧最近且身高高于他的士兵的位置。文章详细解释了算法的逻辑,并提供了一段C语言实现的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 问题描述
  • Maybe you think this problem is about girls and ladies.
    But you're wrong. 'Left dress' means 'Eyes left'. It's used in armed forces. It will make a square more orderly.
    Now several soldiers stand in a line. They are in diffient height or the same. When each of them eyes left, the first man he will see is the nearest man higher than him.
    For each soldier, you should tell me the height of the first man he will see when his eyes left.
  • 输入
  • This problem has several cases.
    The first line of each case is an integer N (1 < N <= 1 000 000).
    Then follows a line with N integers. Indicates the height of each man. (1 <= height <= 1 000 000).
  • 输出
  • For each case, you should output everyone's first man's position. If one has no first man, then output -1.
  • 样例输入
  • 5
    1 3 2 5 8
    4
    5 4 3 2
    
  • 样例输出
  • -1 -1 1 -1 -1
    -1 0 1 2
    
  • 提示
  • 暴力的话,时间复杂度太高,一定会超时,所以得优化,
  • 我的思路是在输入时就完成操作,定义数组pos[],pos[i]表示第个i个人对应的左边第一个比他高的人的位子。
  • 那么显然有如下的推理,当第i个人的高度小于第i-1个人的高度时,那么pos[i]显然就是i-1;
  • 当第i个人的高度等于第i-1个人的高度时,那个pos[i]就是pos[i-1];
  • 当第i个人的高度大于第i-1个人的高度时,需要分情况讨论
  • a).设人的高度存在数组str里,如果str[pos[i-1]]大于str[i],那么pos[i]显然就是pos[i-1],因为第i个人一定比第i-1个要高,而 str[pos[i-1]]大于str[i],那么在 str[pos[i-1]]到str[i-1]里不会有比str[i]高的人,所以可以推知 pos[i]==pos[i-1]
  • b).如果 str[pos[i-1]]小于或等于str[i],那么在  str[pos[i-1]]到str[i-1]的人一定都比str[i]要矮,所以这是只能去str[pos[i-1]]寻找。
  • 如果大家有更好的办法,欢迎给我留言NOJ [1175] Dress, Left Dress! - 深海灬孤独 - Alex
  • 附上我的AC代码
  • #include<stdio.h>
    #include<string.h>

    int pos[1000010];
    int str[1000010];

    int main()
    {
    int n;
    while(~scanf("%d",&n))
    {
    int i=0,j;
    pos[0]=-1;
    for(i=0;i<n;i++)
    {
    scanf("%d",&str[i]);
    if(i>=1)
    {
    if(str[i]==str[i-1])
    pos[i]=pos[i-1];
    else if(str[i]<str[i-1])
    pos[i]=i-1;
    else
    {
    if(str[pos[i-1]]>str[i])
    pos[i]=pos[i-1];
    else
    {
    for(j=pos[i-1];j>=0;j--)
    if(str[j]>str[i])
    break;
    if(j<0)
    pos[i]=-1;
    else
    pos[i]=j;
    }
    }
    }
    }
    for(i=0;i<n-1;i++)
    printf("%d ",pos[i] );
    printf("%d\n",pos[i] );
    }
    return 0;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值