1. 程式人生 > >CF1042D Petya and Array

CF1042D Petya and Array

eof nbsp begin str cto pos main 逆序對數 void

思路:

離散化+樹狀數組(或權值線段樹)。bit數組一定要開夠。和求逆序對數量很像。

實現:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int MAXN = 200005;
 5 ll a[MAXN], b[MAXN], bit[2 * MAXN];
 6 int n;
 7 int lowbit(int x)
 8 {
 9     return x & -x;
10 }
11 ll sum(int x)
12 {
13     ll ans = 0;
14
while (x) 15 { 16 ans += bit[x]; 17 x -= lowbit(x); 18 } 19 return ans; 20 } 21 void add(int i, ll x, int maxn) 22 { 23 while (i <= maxn) 24 { 25 bit[i] += x; 26 i += lowbit(i); 27 } 28 } 29 int main() 30 { 31 ll t; 32 while (cin >> n >> t)
33 { 34 memset(b, 0, sizeof b); 35 memset(bit, 0, sizeof bit); 36 for (int i = 1; i <= n; i++) 37 { 38 cin >> a[i]; 39 b[i] = b[i - 1] + a[i]; 40 } 41 vector<ll> v; 42 for (int i = 0; i <= n; i++) 43 {
44 v.push_back(b[i]); 45 v.push_back(b[i] + t); 46 } 47 sort(v.begin(), v.end()); 48 v.erase(unique(v.begin(), v.end()), v.end()); 49 ll ans = 0; 50 for (int i = n; i >= 1; i--) 51 { 52 int pos = lower_bound(v.begin(), v.end(), b[i]) - v.begin() + 1; 53 add(pos, 1, v.size()); 54 pos = lower_bound(v.begin(), v.end(), b[i - 1] + t) - v.begin() + 1; 55 ans += sum(pos - 1); 56 } 57 cout << ans << endl; 58 } 59 return 0; 60 }

CF1042D Petya and Array