Advertisement
Mihai_Preda

Untitled

Feb 7th, 2021
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int MaxN = 1000010;
  6. const int mod = 1e9 + 7;
  7.  
  8. int v[MaxN], left1[MaxN], left2[MaxN], right1[MaxN], right2[MaxN];
  9.  
  10. int multiply(int a, int b, int c, int d) {
  11.     return (1LL * ((1LL * a * b) % mod) * ((1LL * c * d) % mod)) % mod;
  12. }
  13.  
  14. int main() {
  15.     ios_base::sync_with_stdio(false);
  16.     cin.tie(0);
  17.     //ifstream fin("rectangles.in");
  18.     //ofstream fout("rectangles.out");
  19.     int n;
  20.     cin >> n;
  21.     for (int i = 1; i <= n; i++) {
  22.         cin >> v[i];
  23.         left1[i] = left2[i] = 0;
  24.         right1[i] = right2[i] = n + 1;
  25.     }
  26.  
  27.     stack<int> st1, st2, aux;
  28.     for (int i = 1; i <= n; i++) {
  29.         while (!st2.empty() && v[i] > v[st2.top()]) {
  30.             right2[st2.top()] = i;
  31.             st2.pop();
  32.         }
  33.         while (!st1.empty() && v[i] > v[st1.top()]) {
  34.             right1[st1.top()] = i;
  35.             aux.push(st1.top());
  36.             st1.pop();
  37.         }
  38.         st1.push(i);
  39.         for (; !aux.empty(); aux.pop())
  40.             st2.push(aux.top());
  41.     }
  42.  
  43.     for (; !st1.empty(); st1.pop());
  44.     for (; !st2.empty(); st2.pop());
  45.  
  46.     for (int i = n; i >= 1; i--) {
  47.         while (!st2.empty() && v[i] >= v[st2.top()]) {
  48.             left2[st2.top()] = i;
  49.             st2.pop();
  50.         }
  51.         while (!st1.empty() && v[i] >= v[st1.top()]) {
  52.             left1[st1.top()] = i;
  53.             aux.push(st1.top());
  54.             st1.pop();
  55.         }
  56.         st1.push(i);
  57.         for (; !aux.empty(); aux.pop())
  58.             st2.push(aux.top());
  59.     }
  60.  
  61.     long long sol = 0;
  62.     for (int i = 1; i <= n; i++) {
  63.         if (left1[i] > 0) {
  64.             int a = left1[i] - left2[i];
  65.             int b = right1[i] - i;
  66.             sol = (sol + multiply(a, b, v[i], v[left1[i]])) % mod;
  67.         }
  68.         if (right1[i] < n + 1) {
  69.             int a = i - left1[i];
  70.             int b = right2[i] - right1[i];
  71.             sol = (sol + multiply(a, b, v[i], v[right1[i]])) % mod;
  72.         }
  73.     }
  74.  
  75.     cout << sol << "\n";
  76.     return 0;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement