codeforces 903 D. Almost Difference 线段树

Let’s denote a function

You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
Input

The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.

The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 109) — elements of the array.
Output

Print one integer — the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
Examples
Input

5
1 2 3 1 3

Output

4

Input

4
6 6 5 5

Output

0

Input

4
6 6 4 4

Output

-8

题意大致是给一个数组,统计每对数之间的关系,即当i < j时统计Aj-Ai的值,当|Aj-Ai|<=1时统计为零。

这里提供一个线段树做法,先把线段树所有值置为0,线段树统计区间和,统计序列的值和编号,然后按值排序。在此题中每对值只统计一次,或加正数或加负数,排序后加线段树可转化为加正数或减正数。每次把比当前值>=2的数进入线段树,加个队列进行延迟即可,当前值编号为m,然后统计区间A(1,m-1),B(m+1,n),A为要增加的,B为减去的。综合复杂度nlogn。记得此题爆LL,加上long double即可。

#include <iostream>
#include <algorithm>
#include <cstdio>
struct aaa
{
    long long x,y;
}aa[200001];

struct bbb
{
    long long x,y;
}bb[200002];
bool cmp(aaa A,aaa B)
{
    return A.x<B.x;
}
long double a[6000000];
long long b[6000000],f=0;


void gouzao(long long v,long long l,long long r,long long x,long long y)
{
    if(l==r){a[v]+=y;b[v]=1;return;}
    long long mid=(l+r)/2;
    if(mid>=x)gouzao(v*2,l,mid,x,y);
    else gouzao(v*2+1,mid+1,r,x,y);
    b[v]=b[v*2]+b[v*2+1];
    a[v]=a[v*2]+a[v*2+1];
}
long double chaxun(long long v,long long l,long long r,long long x,long long y)
{
    //std::cout<<l<<" "<<r<<" "<<x<<" "<<y<<std::endl;
    if(l==x&&y==r)
    {
        f+=b[v];
        return a[v];
    }

    long long mid=(l+r)/2;
    if(mid>=y)return chaxun(v*2,l,mid,x,y);
    if(mid<x)return chaxun(v*2+1,mid+1,r,x,y);
    return chaxun(v*2,l,mid,x,mid)+chaxun(v*2+1,mid+1,r,mid+1,y);
}

int main()
{
    long long n;std::cin>>n;

    for(long long i=1;i<=n;i++)
    {
        scanf("%lld",&aa[i].x);
        aa[i].y=i;
    }
    std::sort(aa+1,aa+n+1,cmp);
    long long x=0,y=1;
    long double s=0,g;
    bb[y].x=aa[1].x,bb[y].y=aa[1].y;
    for(long long i=2;i<=n;i++)
    {

        while(x!=y)
        {
            if(bb[x+1].x+1<aa[i].x)gouzao(1,1,n,bb[x+1].y,bb[x+1].x),x++;
            else break;
        }

        if(aa[i].y-1>=1)
        {
            //std::cout<<i<<" "<<aa[i].y<<std::endl;
            f=0;
            g=chaxun(1,1,n,1,aa[i].y-1);
            s+=aa[i].x*f-g;
        }

        if(n>=aa[i].y+1)
        {
            f=0;
            g=chaxun(1,1,n,aa[i].y+1,n);
            s+=g-aa[i].x*f;
        }

        bb[++y].x=aa[i].x;
        bb[y].y=aa[i].y;
    }

    printf("%.0Lf\n",s);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值