Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <map>
- #include <stack>
- //#include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- const ll MOD = 1e9 + 7;
- int main()
- {
- ios_base::sync_with_stdio(false);
- int n;
- cin >> n;
- vector<int> v(n);
- for(int i = 0; i < n; i++) {
- cin >> v[i];
- }
- vector<int> left(n, -1);
- vector<int> right(n, n);
- stack<int> st;
- for(int i = 0; i < n; i++) {
- while(!st.empty() and v[st.top()] > v[i]) {
- st.pop();
- }
- if(st.empty()) {
- left[i] = -1;
- }
- else {
- left[i] = st.top();
- }
- st.push(i);
- }
- stack<int> st2;
- for(int i = n - 1; i >= 0; i--) {
- while(!st2.empty() and v[st2.top()] > v[i]) {
- st2.pop();
- }
- if(st2.empty()) {
- right[i] = n;
- }
- else {
- right[i] = st2.top();
- }
- st2.push(i);
- }
- ll total_subarrays = (ll)n * (ll)(n + 1) / 2;
- total_subarrays %= MOD;
- ll bad_subarrays = 0;
- for(int i = 0; i < n; i++) {
- ll L = i - left[i];
- ll R = right[i] - i;
- bad_subarrays += ((L * R) % MOD);
- bad_subarrays %= MOD;
- }
- cout << (total_subarrays - bad_subarrays) % MOD << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment