Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cstdio>
  4. #include <cstring>
  5. #include <ctime>
  6. #include <cmath>
  7. #include <cctype>
  8. #include <vector>
  9. #include <string>
  10. #include <queue>
  11. #include <stack>
  12. #include <set>
  13. #include <map>
  14. #include <iterator>
  15. #include <functional>
  16. #include <cassert>
  17. #include <algorithm>
  18.  
  19. typedef long long LL;
  20. typedef long double LD;
  21. using namespace std;
  22.  
  23. const int MAX = 100005;
  24.  
  25. int n;
  26. int h[MAX], prev[MAX], next[MAX];
  27.  
  28. int main()
  29. {
  30. freopen("d.in", "r", stdin);
  31. freopen("d.out", "w", stdout);
  32.  
  33. scanf("%d", &n);
  34. for (int i = 1; i <= n; ++i)
  35. scanf("%d", &h[i]);
  36. h[0] = h[n + 1] = 0;
  37.  
  38. stack <int> s;
  39. s.push(0);
  40. for (int i = 1; i <= n; ++i)
  41. {
  42. while (!s.empty() && h[i] <= h[s.top()]) s.pop();
  43. prev[i] = s.empty() ? 0 : s.top();
  44. s.push(i);
  45. }
  46.  
  47. while (!s.empty()) s.pop();
  48. s.push(n + 1);
  49. for (int i = n; i; --i)
  50. {
  51. while (!s.empty() && h[i] <= h[s.top()]) s.pop();
  52. next[i] = s.empty() ? n + 1 : s.top();
  53. s.push(i);
  54. }
  55.  
  56. LL ans = 0;
  57. for (int i = 1; i <= n; ++i)
  58. ans += h[i] - max(h[prev[i]], h[next[i]]);
  59.  
  60. printf("%d\n", ans);
  61.  
  62. return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement