NOJ [1175] Dress, Left Dress!

  • 问题描述
  • 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;
    }


你可能感兴趣的:(NOJ [1175] Dress, Left Dress!)