Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <cstdio>
- #include <cstring>
- #include <ctime>
- #include <cmath>
- #include <cctype>
- #include <vector>
- #include <string>
- #include <queue>
- #include <stack>
- #include <set>
- #include <map>
- #include <iterator>
- #include <functional>
- #include <cassert>
- #include <algorithm>
- typedef long long LL;
- typedef long double LD;
- using namespace std;
- const int MAX = 100005;
- int n;
- int h[MAX], prev[MAX], next[MAX];
- int main()
- {
- freopen("d.in", "r", stdin);
- freopen("d.out", "w", stdout);
- scanf("%d", &n);
- for (int i = 1; i <= n; ++i)
- scanf("%d", &h[i]);
- h[0] = h[n + 1] = 0;
- stack <int> s;
- s.push(0);
- for (int i = 1; i <= n; ++i)
- {
- while (!s.empty() && h[i] <= h[s.top()]) s.pop();
- prev[i] = s.empty() ? 0 : s.top();
- s.push(i);
- }
- while (!s.empty()) s.pop();
- s.push(n + 1);
- for (int i = n; i; --i)
- {
- while (!s.empty() && h[i] <= h[s.top()]) s.pop();
- next[i] = s.empty() ? n + 1 : s.top();
- s.push(i);
- }
- LL ans = 0;
- for (int i = 1; i <= n; ++i)
- ans += h[i] - max(h[prev[i]], h[next[i]]);
- printf("%d\n", ans);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement