F - 我,不是说了能力要平均值么 · 改三

F - 我,不是说了能力要平均值么 · 改三

题目大意

题目给出一个长度为 n n n的序列,求出所有 n × ( n + 1 ) 2 \frac{n \times (n + 1)} {2} 2n×(n+1)个区间的最大值和最小值的和。

答案要对 1 0 9 + 7 10^9+7 109+7取模。

题解

换一个思考角度,考虑每个数能成多少个区间的最值,也就是说它对答案的贡献。

很显然,只要找到左边比它大的数和右边比它大的数,那么中间这一段,最大值都是它自己。

单调栈来维护,求最大值的时候,维护一个单调递减的栈。

一个进栈的时候,将比它小的元素都踢出栈。

一个数在出栈的时候,统计它的贡献,

左边比它的数,就是单调栈里,在它左边的那个数,右边比它大的数,显然就是现在要把它踢出栈的那个元素。

  • 注意:最好也要把栈里的所有元素出栈
  • 即便有取模,也要注意开long long

求最小值同理,就把代码copy一下,改一下符号。

对于算平均值,利用费马小定理求出逆元即可。

时间复杂度

每个元素只进栈一次,也只出栈一次,因此时间复杂度是 O ( n ) O(n) O(n)

Tag

  • 单调栈
  • 费马小定理,逆元

code

//#pragma GCC optimize (2)
//#pragma G++ optimize (2)
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#define G getchar
#define mo %1000000007
using namespace std;

int read()
{
    char ch;
    for(ch = G();ch < '0' || ch > '9';ch = G());
    int n = 0;
    for(;'0' <= ch && ch <= '9';ch = G())n = (n<<1)+(n<<3)+ch-48;
    return n;
}

void write(int x)
{
    if (x > 9)
    {
        write(x / 10);
        putchar(x % 10 + 48);
    }
    else putchar(x + 48);
}

const int N = 1000006;
int a[N] , z[N] , id[N] , top , n;
long long ans;

long long ksm(long long x)
{
    long long s=x , ans = 1;
    int y = 1000000005;
    for (;y;y = y >> 1)
    {
        if (y % 2) ans = ans * s mo;
        s = s * s mo;
    }
    return ans;
}

int main()
{
    freopen("f.in","r",stdin);
    //freopen("f.out","w",stdout);
    n = read();
    for (int i = 1 ; i <= n ; i++) a[i] = read();

    z[top = 1 ] = 2147483647;
    for (int i = 1; i <= n; i++)
    {
        for (;a[i] >= z[top]; top--)
        {
            ans =(ans + (long long )(id[top] - id[top - 1]) * (i - id[top])mo * z[top] mo)mo;
        }
        z[++ top] = a[i];
        id[top] = i;
    }
    for (;top > 1; top --)
        ans =(ans + (long long )(id[top] - id[top - 1]) * (n - id[top] + 1)mo * z[top] mo)mo;


    z[top = 1 ] = -2147483647;
    for (int i = 1; i <= n; i++)
    {
        for (;a[i] <= z[top]; top--)
        {
            ans =(ans + (long long )(id[top] - id[top - 1]) * (i - id[top])mo * z[top] mo)mo;
        }
        z[++ top] = a[i];
        id[top] = i;
    }
    for (;top > 1; top --)
        ans =(ans + (long long )(id[top] - id[top - 1]) * (n - id[top] + 1)mo * z[top] mo)mo;

    printf("%lld\n", ans * ksm((long long)n * (n + 1) mo ) mo);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值