Josif_tepe

Untitled

Feb 27th, 2026
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  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;
  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.     stack<int> st2;
  32.     for(int i = n - 1; i >= 0; i--) {
  33.         while(!st2.empty() and v[st2.top()] > v[i]) {
  34.             st2.pop();
  35.         }
  36.         if(!st2.empty()) {
  37.             right[i] = st2.top();
  38.         }
  39.         st2.push(i);
  40.     }
  41.    
  42.     ll total_subarrays = n * (n + 1) / 2;
  43.     total_subarrays %= MOD;
  44.    
  45.     ll bad_subarrays = 0;
  46.     for(int i = 0; i < n; i++) {
  47.         ll L = i - left[i], 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.     return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment