Advertisement
Abrar_Al_Samit

Second Order Difference Array (ABC407F)

Jun 9th, 2025
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int nax = 2e5 + 4;
  5. int n, a[nax];
  6. int L[nax], R[nax];
  7. long long ans[nax];
  8. void PlayGround() {
  9.     cin>>n;
  10.     for(int i=1; i<=n; ++i) {
  11.         cin>>a[i];
  12.     }
  13.  
  14.     int stk[n + 10] = {0}, top = 0;
  15.     for(int i=1; i<=n; ++i) {
  16.         while(top && a[stk[top]] <= a[i]) R[stk[top--]] = i;
  17.         stk[++top] = i;
  18.     }
  19.     while(top) R[stk[top--]] = n+1;
  20.     for(int i=n; i>0; --i) {
  21.         while(top && a[stk[top]] < a[i]) L[stk[top--]] = i;
  22.         stk[++top] = i;
  23.     }
  24.  
  25.  
  26.     //second order difference array works because the number of times a[i]
  27.     //gets added to each subarray length has the following pattern:
  28.     //1 2 3 4 5 6 ... x x x x x x x-1 x-2 x-3 x-4 ... 3 2 1 0
  29.     // in the first order difference array :
  30.     //1 1 1 1 1 1 ... 0 0 0 0 0 0 -1 -1 -1 -1 -1 ... -1 -1 -1 0 0 0 ...
  31.     //in the second order difference array :
  32.     //1 0 0 0 0 0 ... -1 0 0 0 0 0 -1 0 0 0 0 0 0 ... 0 0 0 0 1 0 0 0 ...
  33.  
  34.     for(int i=1; i<=n; ++i) {
  35.         ans[1] += a[i];
  36.         ans[i - L[i] + 1] -= a[i];
  37.         ans[R[i] - i + 1] -= a[i];
  38.         ans[R[i] - L[i] + 1] += a[i];
  39.     } // now ans is the second order difference array of actual answer
  40.     for(int i=1; i<=n; ++i) {
  41.         ans[i] += ans[i-1];
  42.     } // first order difference array
  43.     for(int i=1; i<=n; ++i) {
  44.         ans[i] += ans[i-1];
  45.     } // actual ans
  46.  
  47.     for(int i=1; i<=n; ++i) {
  48.         cout<<ans[i]<<'\n';
  49.     }
  50.  
  51. }
  52. int main() {
  53.     int t = 1;
  54.     while(t--)
  55.         PlayGround();
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement