1. 程式人生 > >Petya and Array CodeForces - 1042D (樹狀數組)

Petya and Array CodeForces - 1042D (樹狀數組)

byte get .org sin posit width cli 而不是 class

D. Petya and Array time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output

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 (lrl≤r) such that al+al+1+?+ar?1+ar<tal+al+1+?+ar?1+ar<t.

Input

The first line contains two integers

nn and tt (1n200000,|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.

Output

Print the number of segments in Petya‘s array with the sum of elements less than

tt.

Examples Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note

In the first example the following segments have sum less than 44:

  • [2,2][2,2], sum of elements is ?1?1
  • [2,3][2,3], sum of elements is 22
  • [3,3][3,3], sum of elements is 33
  • [4,5][4,5], sum of elements is 33
  • [5,5][5,5], sum of elements is ?1?1

先補上樹狀數組的解法

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 }
View Code

Petya and Array CodeForces - 1042D (樹狀數組)