TOJ2640 The nearest taller cow

描述

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。

#include<stdio.h>
#include<string.h>
#include<string>
#include<math.h>
#include<vector>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
int a[1000100],b[1000100],c[1000100];
//a为原序列,b存左边比它大的最近的坐标,c存右边 
int main()
{
	int n,i,j,k,sum,max;
	while(scanf("%d",&n)!=EOF)
	{
		max=-1;
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			if(a[i]>max)
			max=a[i];
		}		
		memset(b,0,sizeof b);
		memset(c,0,sizeof c);
		b[1]=n;//最左边的数左边没有比它大的了
		c[n]=0;//最右边的数右边没有比它大的了 
		for(i=1;i<=n;i++)
		{
			for(j=i-1;j>0;)
			{
				if(a[j]>a[i])
				{
					b[i]=j;
					break;
				} 
				else
				{
					if(b[i])
					j=b[i];
					else
					j--;
				}
			}
			for(k=i+1;k<=n;)
			{
				if(a[k]>a[i])
				{
					c[i]=k;
					break;
				} 
				else
				{
					if(c[i])
					k=c[i];
					else
					k++;
				}
			}
		}
		//for(i=1;i<=n;i++)
		//printf("%d ",b[i]);
		//printf("\n");
		//for(i=1;i<=n;i++)
		//printf("%d ",c[i]);
		sum=0;
		for(i=1;i<=n;i++)
		{
			if(a[i]==max)
			sum+=n;
			else if(b[i]==0)
			sum+=fabs(c[i]-i);
			else if(c[i]==0)
			sum+=fabs(b[i]-i);
			else if(fabs(b[i]-i)>fabs(c[i]-i))
			sum+=fabs(c[i]-i);
			else
			sum+=fabs(b[i]-i);
			//printf("sum:%d\n",sum);
		}
		//printf("%d\n",sum); 
		double s;
		s=1.0*sum/n;
		printf("%.2lf\n",s);
	} 
} 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值