Josif_tepe

Untitled

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