题意:给定一个长度为 n 的正整数序列,求出有多少个连续子序列的平均值不小于 k。
思路:
对于平均值的问法,先所有a[i]-k,然后问题就转化成有多少个区间,其和大于等于0。
若先处理前缀和,那么就是在问,我当前如果固定了右端点是 i i i,那么我要知道前面有多少个数是 < = s u m [ i ] <=sum[i] <=sum[i]的,这个就转化成一个cdq分治的问题了,类似于求逆序对。
AC代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include <queue>
#include<sstream>
#include <stack>
#include <set>
#include <bitset>
#include<vector>
#define FAST ios::sync_with_stdio(false)
#define abs(a) ((a)>=0?(a):-(a))
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define rep(i,a,n) for(int i=a;i<=n;++i)
#define per(i,n,a) for(int i=n;i>=a;--i)
#define endl '\n'
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PII;
const int maxn = 2e5+200;
const int inf=0x3f3f3f3f;
const double eps = 1e-7;
const double pi=acos(-1.0);
const int mod = 1e9+7;
inline int lowbit(int x){return x&(-x);}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
void ex_gcd(ll a,ll b,ll &d,ll &x,ll &y){if(!b){d=a,x=1,y=0;}else{ex_gcd(b,a%b,d,y,x);y-=x*(a/b);}}//x=(x%(b/d)+(b/d))%(b/d);
inline ll qpow(ll a,ll b,ll MOD=mod){ll res=1;a%=MOD;while(b>0){if(b&1)res=res*a%MOD;a=a*a%MOD;b>>=1;}return res;}
inline ll inv(ll x,ll p){return qpow(x,p-2,p);}
inline ll Jos(ll n,ll k,ll s=1){ll res=0;rep(i,1,n+1) res=(res+k)%i;return (res+s)%n;}
inline ll read(){ ll f = 1; ll x = 0;char ch = getchar();while(ch>'9'||ch<'0') {if(ch=='-') f=-1; ch = getchar();}while(ch>='0'&&ch<='9') x = (x<<3) + (x<<1) + ch - '0', ch = getchar();return x*f; }
int dir[4][2] = { {1,0}, {-1,0},{0,1},{0,-1} };
ll sum1[maxn];
ll sum2[maxn];
ll up = 32000+500;
void add(ll pos, ll y) //在pos位置+y,对d
{
for(ll i=pos;i<=up;i+=lowbit(i))
sum1[i] += y, sum2[i] += pos*y; //从这个位置开始,包含pos项的sum都改变。 sum1是d[i]的前缀和,sum2是d[i]*i的前缀和,sum1*pos-sum2就是a的前缀和
}
void add_range(ll l, ll r,ll x)
{
add(l,x), add(r+1,-x);
}
ll ask_for_one(ll p)
{
ll ans = 0;
for(ll i=p;i>=1;i-=lowbit(i))
ans += sum1[i];
return ans;
}
ll ask(ll p)
{
ll ans = 0;
for(ll i=p;i>=1;i-=lowbit(i))
ans += ((p+1)*sum1[i] - sum2[i]);
return ans;
}
typedef struct Pos
{
ll id;
ll val;
bool operator < (const Pos &a) const{
if(val != a.val)
return val < a.val;
return id < a.id;
}
}P;
P a[maxn];
ll sum[maxn];
int main()
{
ll n = read(), k = read();
up = n+500;
ll x = 0;
sum[0] = -k;
rep(i,1,n) x = read(), sum[i] = sum[i-1] + x-k;
rep(i,0,n) a[i].val = sum[i], a[i].id = i+1;
sort(a,a+1+n);
ll ans = 0;
rep(i,0,n)
{
ans += ask(a[i].id);
add_range(a[i].id,a[i].id,1);
}
cout<<ans<<endl;
return 0;
}