Josif_tepe

Untitled

Feb 27th, 2026
143
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 <cstring>
  6. #include <cmath>
  7. using namespace std;
  8. typedef long long ll;
  9. const ll MOD = 1e9 + 7;
  10. int main() {
  11.     ios_base::sync_with_stdio(false);
  12.     ll 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.    
  21.     vector<int> left(n, -1), right(n, n);
  22.    
  23.     stack<int> st;
  24.     for(int i = 0; i < n; i++) {
  25.         while(!st.empty() and v[st.top()] > v[i]) {
  26.             st.pop();
  27.         }
  28.         if(!st.empty()) {
  29.             left[i] = st.top();
  30.         }
  31.         st.push(i);
  32.     }
  33.    
  34.     stack<int> st2;
  35.     for(int i = n - 1; i >= 0; i--) {
  36.         while(!st2.empty() and v[st2.top()] > v[i]) {
  37.             st2.pop();
  38.         }
  39.         if(!st2.empty()) {
  40.             right[i] = st2.top();
  41.         }
  42.         st2.push(i);
  43.     }
  44.    
  45.     ll total_subarrays = n * (n + 1) / 2;
  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.  
  59.    
  60.  
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment