zoukankan      html  css  js  c++  java
  • 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);
    }

    每天刷题,身体棒棒!

  • 相关阅读:
    Dr.Watson
    得到当前操作系统的版本的
    屏蔽回车关闭对话框事件
    一个发邮件的类(用CDO实现)
    怎样配置SQL Server发送电子邮件
    无进程DLL木马的又一开发思路与实现
    Write AutoUpdating Apps with .NET and the Background Intelligent Transfer Service API
    WINDOWS编程入门一个初级问题的分析
    智能客户端技术总结(一)
    【.NET】C#.NET ADO.NET数据访问模型概述
  • 原文地址:https://www.cnblogs.com/stxy-ferryman/p/7491840.html
Copyright © 2011-2022 走看看