Josif_tepe

Untitled

Feb 26th, 2026
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <stack>
  5. using namespace std;
  6. typedef long long ll;
  7. const ll MOD = 1e9 + 7;
  8. int main() {
  9.     ios_base::sync_with_stdio(false);
  10.     ll n;
  11.     cin >> n;
  12.    
  13.     vector<int> v(n);
  14.     for(int i = 0; i < n; i++) {
  15.         cin >> v[i];
  16.     }
  17.    
  18.     vector<int> left(n, -1), right(n, n);
  19.    
  20.     stack<int> st, st2;
  21.     for(int i = 0; i < n; i++) {
  22.         while(!st.empty() and v[st.top()] > v[i]) {
  23.             st.pop();
  24.         }
  25.         if(!st.empty()) {
  26.             left[i] = st.top();
  27.         }
  28.         st.push(i);
  29.     }
  30.    
  31.     for(int i = n - 1; i >= 0; i--) {
  32.         while(!st2.empty() and v[st2.top()] > v[i]) {
  33.             st2.pop();
  34.         }
  35.         if(!st2.empty()) {
  36.             right[i] = st2.top();
  37.         }
  38.         st2.push(i);
  39.     }
  40.    
  41.     ll total_subarrays = n * (n + 1) / 2;
  42.     total_subarrays %= MOD;
  43.    
  44.     ll bad_subarrays = 0;
  45.     for(int i = 0; i < n; i++) {
  46.         ll L = (i - left[i]);
  47.         ll R = (right[i] - i);
  48.        
  49.         bad_subarrays += (L * R) % MOD;
  50.         bad_subarrays %= MOD;
  51.     }
  52.    
  53.     cout << (total_subarrays - bad_subarrays + MOD) % MOD << endl;
  54.    
  55.    
  56.    
  57.     return 0;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment