hdu 5805 D - NanoApe Loves Sequence 记录最大值dp

来源:互联网 发布:ubuntu系统字体 编辑:程序博客网 时间:2024/06/05 11:42
NanoApe, the Retired Dog, has returned back to prepare for the National Higher Education Entrance Examination! 

In math class, NanoApe picked up sequences once again. He wrote down a sequence withnn numbers on the paper and then randomly deleted a number in the sequence. After that, he calculated the maximum absolute value of the difference of each two adjacent remained numbers, denoted as FF

Now he wants to know the expected value of FF, if he deleted each number with equal probability.
Input
The first line of the input contains an integer TT, denoting the number of test cases. 

In each test case, the first line of the input contains an integer nn, denoting the length of the original sequence. 

The second line of the input contains nn integers A1,A2,...,AnA1,A2,...,An, denoting the elements of the sequence. 

1T10, 3n100000, 1Ai1091≤T≤10, 3≤n≤100000, 1≤Ai≤109
Output
For each test case, print a line with one integer, denoting the answer. 

In order to prevent using float number, you should print the answer multiplied by nn.
Sample Input
141 2 3 4
Sample Output

6

题意:退役狗 NanoApe 滚回去学文化课啦!
在数学课上,NanoApe 心痒痒又玩起了数列。他在纸上随便写了一个长度为 nn 的数列,他又根据心情随便删了一个数,这样他得到了一个新的数列,然后他计算出了所有相邻两数的差的绝对值的最大值。
他当然知道这个最大值会随着他删了的数改变而改变,所以他想知道假如全部数被删除的概率是相等的话,差的绝对值的最大值的期望是多少。

数学期望的公式 xi*pi的和

思路:这个题最后乘以n所以我们直接算出所有差的绝对值的和即可;

数据量这么大暴力肯定会超时,那么我们不妨这样想,由于删除一个元素(除两边)可能会影响到第1第2第3大的值,所以我们不妨

正向求一遍 a[i]之前元素的最大值,反向求一遍a[i]元素之后的最大值,当删除中间的一个元素时比较 abs(a[i+1]-a[i-1])和其

左右的最大值即可;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 100010
#define LL long long
using namespace std;
LL a[N],l[N],r[N];
int n,t;
int main()
{     int i;
      cin>>t;
      while(t--)
      {    cin>>n;
          for(i=1;i<=n;i++)
          scanf("%lld",&a[i]);
          memset(l,0,sizeof(l));
          memset(r,0,sizeof(r));
          for(i=2;i<=n;i++)
          l[i]=max(abs(a[i]-a[i-1]),l[i-1]);
          for(i=n-1;i>=1;i--)
          r[i]=max(abs(a[i+1]-a[i]),r[i+1]);
          LL sum=0;
 for(i=1;i<=n;i++)
 {   if(i==1)
     sum+=r[2];
     if(i==n)
     sum+=l[n-1];
     if(i>1&&i<n)
     sum+=max(max(abs(a[i+1]-a[i-1]),l[i-1]),r[i+1]);
 }        
 printf("%lld\n",sum);
      }
      return 0;
}

1 0