题目
题意: 给定数组a,求有多少个数对(l,r)满足s[r] - s[l-1] < t. (-1e9<=a[i]<=1e9)
思路: 如果都是正数,双指针或者二分都行。但是有负数,就不能这么做了。找一下等价关系,对于每一个右端点r,找多少个数满足s[r] - t < s[l-1].可以动态维护前缀和,之后树状数组查询。但是前缀和太大,需要离散化之后才能扔到树状数组里。
时间复杂度: O(nlogn)
代码:
// Problem: 合适数对
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/description/4319/
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<complex>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<unordered_map>
#include<list>
#include<set>
#include<queue>
#include<stack>
#define OldTomato ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
#define fir(i,a,b) for(int i=a;i<=b;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define p_ priority_queue
// round() 四舍五入 ceil() 向上取整 floor() 向下取整
// lower_bound(a.begin(),a.end(),tmp,greater<ll>()) 第一个小于等于的
// #define int long long //QAQ
using namespace std;
typedef complex<double> CP;
typedef pair<int,int> PII;
typedef long long ll;
// typedef __int128 it;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const ll inf = 1e18;
const int N = 2e5+10;
const int M = 1e6+10;
const int mod = 1e9+7;
const double eps = 1e-6;
inline int lowbit(int x){ return x&(-x);}
template<typename T>void write(T x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9)
{
write(x/10);
}
putchar(x%10+'0');
}
template<typename T> void read(T &x)
{
x = 0;char ch = getchar();ll f = 1;
while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
int n,k,T;
ll m;
int a[N];
ll s[N];
ll ans = 0;
ll tr[N<<1];
vector<ll> va;
void add(int x,int k)
{
for(int i=x;i<(N<<1);i+=lowbit(i)) tr[i] += k;
}
int sum(int x)
{
int res = 0;
for(int i=x;i;i-=lowbit(i)) res += tr[i];
return res;
}
ll find(ll x)
{
return lower_bound(va.begin(),va.end(),x)-va.begin()+1;
}
void solve()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;++i) cin>>a[i],s[i] = s[i-1] + a[i];
for(int i=0;i<=n;++i)
{
va.push_back(s[i]);
va.push_back(s[i]-m);
}
sort(va.begin(),va.end());
va.erase(unique(va.begin(),va.end()),va.end());
add(find(s[0]),1); //l-1从0开始
for(int i=1;i<=n;++i) //右端点
{
int tmp = sum((N<<1)-1) - sum(find(s[i]-m)); //多少个l-1 > s[r] - m的
ans += tmp;
add(find(s[i]),1); //将当前端点加进去
}
cout<<ans;
}
signed main(void)
{
T = 1;
// OldTomato; cin>>T;
// read(T);
while(T--)
{
solve();
}
return 0;
}