Codeforce 1042D

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37129433/article/details/82792535

Petya and Array
题 意:给你一个含有n个元素的数组,有多少对[l,r]时刻a[l]+…+a[r]的值小于t。

数据范围:
1<=n<=2e5
|t|<=2e14
|ai|<=1e9

输入样例:

5 4
5 -1 3 4 -1

输出样例:

5

思 路:这个公式是sum[r]-sum[l-1] < t 也就是sum[r] - t < sum[l]。那么我们也就可以枚举r,看有多少个l<r,sum[l] > sump[r]-t。
因为sum[x]值很大,需要离散化一下,就行。

#include<bits/stdc++.h>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define debug(x) cout<<#x<<" = "<<(x)<<endl;
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 5;
ll pre[maxn],sum[maxn<<2],com[maxn];
ll a[maxn];
int n,len;
ll t;
int getid(ll x){
    return lower_bound(com+1,com+1+len,x)-com;
}
void PushUp(int rt){
    sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
ll query(int L,int R,int l,int r,int rt){
    if(L<=l && r<=R){
        return sum[rt];
    }
    int m = (l+r)/2;ll ans = 0;
    if(L<=m) ans+=query(L,R,lson);
    if(R>m)ans+=query(L,R,rson);
    return ans;
}
void update(int pos,int l,int r,int rt){
    if(l == r){
        sum[rt]++;
        return ;
    }
    int m = (l+r)/2;
    if(pos<=m)update(pos,lson);
    else update(pos,rson);
    PushUp(rt);
}
int main() {
    //freopen("input.txt","r",stdin);
    scanf("%d %lld",&n,&t);
    for(int i=1; i<=n; i++) {
        scanf("%lld",&a[i]);
        pre[i] = pre[i-1] + a[i];
        com[i] = pre[i];
    }
    sort(com+1,com+1+n);
    len = unique(com+1,com+1+n)-(com+1);

    ll ans = 0;
    for(int i=1; i<=n; i++) {
        int id = getid(pre[i]);
        if(pre[i]<t) ans++;
        int pos = upper_bound(com+1,com+1+len,pre[i]-t)-(com);
        ll temp = 0;
        if(pos<=len)temp=query(pos,len,1,len,1);
        ans+=temp;
        update(id,1,len,1);
    }
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37129433/article/details/82792535