CodeForces - 846F Random Query(期望)

You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed).

Input

The first line contains one integer number n (1 ≤ n ≤ 106). The second line containsn integer numbers a1a2, ... an (1 ≤ ai ≤ 106) — elements of the array.

Output

Print one number — the expected number of unique elements in chosen segment.

Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 — formally, the answer is correct if CodeForces - 846F Random Query(期望), where xis jury's answer, and y is your answer.

Example

Input
2
1 2
Output
1.500000
Input
2
2 2
Output
1.000000

题意:给你一个序列a,随机生成l,r有可能l>r,则看做r,l处理。将权值定义为l-r中不同数字的个数,求期望。

题解:第一道期望题!首先肯定是想暴力,枚举每一种l,r,扫l-r中不同的数的个数,复杂度(n^3),考虑优化,对于每个值k,他能对前一个值为k的位置到如今的所有l和之后的所有r做贡献,贡献为(i-pre[k])*(n-i+1),因为l,r可互换,所以有两种可能性,所以贡献为(i-pre[k])*(n-i+1)。
因为l=r的情况只算一种,但之前算了两遍,所以应该减去。 代码如下:
#include<cstdio>
#include<algorithm>
using namespace std; long long pre[],n,i,j,ans; int main()
{
scanf("%lld",&n);
ans-=n;
for(i=;i<=n;i++)
{
long long x;
scanf("%lld",&x);
ans+=(i-pre[x])*(n-i+)*;
pre[x]=i;
}
double hehe=(double)ans/(n*n);
printf("%.6lf",hehe);
}

每天刷题,身体棒棒!

上一篇:Linux 下的分屏利器-tmux安装、原理及使用


下一篇:jQuery跳转到页面指定位置