TOJ2640 The nearest taller cow

小灰灰 2022-05-30 10:14 75阅读 0赞

描述

Farmer Zhao’s N cows (1 ≤ N ≤ 1,000,000) are lined up in a row. So each cow can see the nearest cow which is taller than it. Your task is simple, given the height (0 < height ≤ 109) of each cow lined up in the row, to calculate the distance between each cow and its nearest taller cow, if it is the tallest cow in the row, such distance is regarded as n. You should output the average distance.

输入

For each test case:
Line 1: One integers, N
Lines 2: N integers. The ith integer is the height of the ith cow in the row.

输出

The average distance to their nearest taller cow, rounded up to 2 decimals.

样例输入

7

7 6 5 8 6 4 10

样例输出

2.43

看n这么大吓我一跳,麻瓜的我依旧选择暴力好了…

用b,c数组可以优化一下,可以省一点时间,跳过一些区间。

最后计算sum的时候要考虑几种情况,因为一开始都设置为0了,

10

2 3 4 5 4 3 2 1 8 9

比如这组数据。如果不考虑b[i]!=0的话,5这个位置b[i]=0,c[i]=9,他会取4,而不是5。

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<string>
  4. #include<math.h>
  5. #include<vector>
  6. #include<map>
  7. #include<iostream>
  8. #include<algorithm>
  9. using namespace std;
  10. int a[1000100],b[1000100],c[1000100];
  11. //a为原序列,b存左边比它大的最近的坐标,c存右边
  12. int main()
  13. {
  14. int n,i,j,k,sum,max;
  15. while(scanf("%d",&n)!=EOF)
  16. {
  17. max=-1;
  18. for(i=1;i<=n;i++)
  19. {
  20. scanf("%d",&a[i]);
  21. if(a[i]>max)
  22. max=a[i];
  23. }
  24. memset(b,0,sizeof b);
  25. memset(c,0,sizeof c);
  26. b[1]=n;//最左边的数左边没有比它大的了
  27. c[n]=0;//最右边的数右边没有比它大的了
  28. for(i=1;i<=n;i++)
  29. {
  30. for(j=i-1;j>0;)
  31. {
  32. if(a[j]>a[i])
  33. {
  34. b[i]=j;
  35. break;
  36. }
  37. else
  38. {
  39. if(b[i])
  40. j=b[i];
  41. else
  42. j--;
  43. }
  44. }
  45. for(k=i+1;k<=n;)
  46. {
  47. if(a[k]>a[i])
  48. {
  49. c[i]=k;
  50. break;
  51. }
  52. else
  53. {
  54. if(c[i])
  55. k=c[i];
  56. else
  57. k++;
  58. }
  59. }
  60. }
  61. //for(i=1;i<=n;i++)
  62. //printf("%d ",b[i]);
  63. //printf("\n");
  64. //for(i=1;i<=n;i++)
  65. //printf("%d ",c[i]);
  66. sum=0;
  67. for(i=1;i<=n;i++)
  68. {
  69. if(a[i]==max)
  70. sum+=n;
  71. else if(b[i]==0)
  72. sum+=fabs(c[i]-i);
  73. else if(c[i]==0)
  74. sum+=fabs(b[i]-i);
  75. else if(fabs(b[i]-i)>fabs(c[i]-i))
  76. sum+=fabs(c[i]-i);
  77. else
  78. sum+=fabs(b[i]-i);
  79. //printf("sum:%d\n",sum);
  80. }
  81. //printf("%d\n",sum);
  82. double s;
  83. s=1.0*sum/n;
  84. printf("%.2lf\n",s);
  85. }
  86. }

发表评论

表情:
评论列表 (有 0 条评论,75人围观)

还没有评论,来说两句吧...

相关阅读