标签:etc base ext tle art clipboard tput space required
Petya has an array aa consisting of nn integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than tt. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l,rl,r (l≤rl≤r) such that al+al+1+?+ar?1+ar<tal+al+1+?+ar?1+ar<t.
The first line contains two integers nn and tt (1≤n≤200000,|t|≤2?10141≤n≤200000,|t|≤2?1014).
The second line contains a sequence of integers a1,a2,…,ana1,a2,…,an (|ai|≤109|ai|≤109) — the description of Petya‘s array. Note that there might be negative, zero and positive elements.
Print the number of segments in Petya‘s array with the sum of elements less than tt.
5 4
5 -1 3 4 -1
5
3 0
-1 2 -3
4
4 -1
-2 1 -2 3
3
In the first example the following segments have sum less than 44:
先补上树状数组的解法
sum[i] - sum[j] < t , 1 <= j < i,所以sum[i] - t < sum[j]
因为j是i之前的前缀和,那么我们可以找当前sum[j],小于等于sum[i]-t的,然后用ans+=(i-query),然后一直wa,看了网上题解,加入一个0的虚拟节点后(相当于每个当前前缀和),树状数组记录当前时刻1到n+1,而不是1到n;
这样就可以知道当前前缀和之前的前缀和出现情况。
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 typedef long long ll; 5 const int maxn = 2e5+5; 6 7 ll tree[maxn]; 8 ll sum[maxn]; 9 ll num[maxn]; 10 int n; 11 ll t; 12 13 int lowbit(int x) 14 { 15 return x&(-x); 16 } 17 18 void add(int x) 19 { 20 for(int i=x;i<=n+1;i+=lowbit(i)) 21 { 22 tree[i]++; 23 } 24 } 25 26 ll query(int x) 27 { 28 ll ans = 0; 29 for(int i=x;i>0;i-=lowbit(i)) 30 { 31 ans += tree[i]; 32 } 33 return ans; 34 } 35 36 int main() 37 { 38 scanf("%d%lld",&n,&t); 39 for(int i=1;i<=n;i++) 40 { 41 scanf("%lld",&sum[i]); 42 sum[i] += sum[i-1]; 43 num[i] = sum[i]; 44 } 45 sort(num,num+n+1); 46 ll ans = 0; 47 for(int i=1;i<=n;i++) 48 { 49 add(lower_bound(num,num+n+1,sum[i-1])-num+1); 50 ans += i - query(upper_bound(num,num+n+1,sum[i]-t)-num); 51 } 52 printf("%lld\n",ans); 53 }
Petya and Array CodeForces - 1042D (树状数组)
标签:etc base ext tle art clipboard tput space required
原文地址:https://www.cnblogs.com/iwannabe/p/9753998.html