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 , 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[1000010],n,i,j,ans;

int main()
{
    scanf("%lld",&n);
    ans-=n;
    for(i=1;i<=n;i++)
    {
        long long x;
        scanf("%lld",&x);
        ans+=(i-pre[x])*(n-i+1)*2;
        pre[x]=i;
    }
    double hehe=(double)ans/(n*n);
    printf("%.6lf",hehe);
}

 

 

 

 

每天刷题,身体棒棒!

转载于:https://www.cnblogs.com/stxy-ferryman/p/7491840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值