思路:
从前往后遍历i,对于每个i,使用树状数组统计episode数大于等于i的season数,本次统计结束之后,把长度为i的season从树状数组中删掉,避免影响下次统计。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int MAXN = 200005; 4 int bit[MAXN], a[MAXN], n; 5 vector<int> v[MAXN]; 6 int lowbit(int x) { return x & -x; } 7 void add(int i, int x) 8 { 9 while (i <= n) { bit[i] += x; i += lowbit(i); } 10 } 11 int sum(int i) 12 { 13 int ans = 0; 14 while (i) { ans += bit[i]; i -= lowbit(i); } 15 return ans; 16 } 17 int main() 18 { 19 while (cin >> n) 20 { 21 memset(bit, 0, sizeof bit); 22 for (int i = 1; i < MAXN; i++) v[i].clear(); 23 for (int i = 1; i <= n; i++) 24 { 25 cin >> a[i]; 26 add(i, 1); 27 if (a[i] < MAXN) v[a[i]].push_back(i); 28 } 29 long long ans = 0; 30 for (int i = 1; i <= n; i++) 31 { 32 int tmp = sum(min(a[i], n)) - sum(i); 33 if (tmp > 0) ans += tmp; 34 for (int j = 0; j < v[i].size(); j++) add(v[i][j], -1); 35 } 36 cout << ans << endl; 37 } 38 return 0; 39 }