NanoApe Loves Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/131072 K (Java/Others)
Total Submission(s): 1323 Accepted Submission(s): 521
Description
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 with nn 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 T, denoting the number of test cases.
In each test case, the first line of the input contains an integer n, denoting the length of the original sequence.
The second line of the input contains n integers A1,A2,...,An, denoting the elements of the sequence.
1≤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 n.
Sample Output
141 2 3 4
Sample Output
6
思路
题意:
退役狗 NanoApe 滚回去学文化课啦! 在数学课上,NanoApe 心痒痒又玩起了数列。他在纸上随便写了一个长度为 n 的数列,他又根据心情随便删了一个数,这样他得到了一个新的数列,然后他计算出了所有相邻两数的差的绝对值的最大值。 他当然知道这个最大值会随着他删了的数改变而改变,所以他想知道假如全部数被删除的概率是相等的话,差的绝对值的最大值的期望是多少。(为防止精度问题,你需要输出答案乘上n后的值)
题解:因为最后答案要乘 n ,所以题目变成求,对于每个数,删除它后数列中所有相邻两数的绝对值的最大值的总和。那么我们可以用两个数组求解问题。一个数组保存当前位置及其左边,相邻两数的差的绝对值的最大值,一个数组存当前位置及其右边,相邻两数的差的绝对值的最大值。删除当前位置,那么删除后的数列的相邻两数的绝对值的最大值只需要比较 abs(num[i-1]-num[i+1]),f[i-1],g[i+1]的大小。
#include<bits/stdc++.h> using namespace std; const int maxn = 100005; typedef __int64 LL; int num[maxn],f[maxn],g[maxn]; int main() { int T; scanf("%d",&T); while (T--) { int N; scanf("%d",&N); scanf("%d",&num[1]); f[0] = 0; for (int i = 2;i <= N;i++) { scanf("%d",&num[i]); f[i] = max(f[i-1],abs(num[i] - num[i-1])); } g[N] = 0; for (int i = N - 1;i > 0;i--) { g[i] = max(g[i+1],abs(num[i+1] - num[i])); } LL res = 0; for (int i = 2;i < N;i++) { res += max(abs(num[i-1]-num[i+1]),max(f[i-1],g[i+1])); } res += g[2] + f[N-1]; printf("%I64d\n",res); } return 0; }