• CodeForces


    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);
    }

    每天刷题,身体棒棒!

  • 相关阅读:
    Python自动截图html页面
    filebeat+kafka+logstash+Elasticsearch+Kibana日志收集系统搭建
    k8s重要概念
    1721. 使括号有效的最少添加
    167. 链表求和
    272. 爬楼梯 II
    1609. 链表的中间结点
    SQL server查看触发器是否被禁用
    C#窗体内控件大小随窗体等比例变化
    微信接口返回码参考表
  • 原文地址:https://www.cnblogs.com/stxy-ferryman/p/7491840.html
Copyright © 2020-2023  润新知