danielvitor23

M - Friendship

Jul 15th, 2023
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define fi first
  3. #define se second
  4. using namespace std;
  5.  
  6. typedef long long i64;
  7.  
  8. const int MAXN = 500010;
  9.  
  10. int n;
  11. int ft[MAXN];
  12.  
  13. void add(int idx, int val) {
  14.     for (; idx <= n; idx += (idx & -idx)) {
  15.         ft[idx] += val;
  16.     }
  17. }
  18.  
  19. int get(int idx) {
  20.     int ans = 0;
  21.     for (; idx > 0; idx -= (idx & -idx)) {
  22.         ans += ft[idx];
  23.     }
  24.     return ans;
  25. }
  26.  
  27. void add_range(int l, int r, int val) {
  28.     l = max(1, l); r = min(r, n);
  29.     add(l, val);
  30.     add(r + 1, -val);
  31. }
  32.  
  33. int main() {
  34.   cin.tie(0)->sync_with_stdio(0);
  35.  
  36.   cin >> n;
  37.  
  38.   vector<int> a(n + 1), b(n + 1);
  39.  
  40.     vector<pair<int, int>> ranges;
  41.   for (int i = 1; i <= n; i++) {
  42.     cin >> a[i];
  43.         if (a[i])
  44.             ranges.push_back({ max(1, i - a[i]), i });
  45.   }
  46.  
  47.     sort(ranges.begin(), ranges.end());
  48.  
  49.   for (int i = 1; i <= n; i++) {
  50.     cin >> b[i];
  51.         add_range(i + 1, i + b[i], 1);
  52.   }
  53.  
  54.     i64 ans = 0;
  55.     int curr = 1;
  56.  
  57.     for (int i = 0; i < (int)ranges.size(); ++i) {
  58.         while (curr <= n and curr < ranges[i].fi) {
  59.             add_range(curr + 1, curr + b[curr], -1);
  60.             ++curr;
  61.         }
  62.         ans += get(ranges[i].se);
  63.     }
  64.  
  65.     cout << ans << '\n';
  66. }
Advertisement
Add Comment
Please, Sign In to add comment