Guest User

Min Subarray

a guest
Oct 5th, 2016
982
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define f(i,a,b) for(int i = (a); i <= (b); i++)
  3.  
  4. typedef long long ll;
  5. using namespace std;
  6.  
  7. int N, Par[200005], L[200005], R[200005], In[200005];
  8. pair<int,int> A[200005];
  9.  
  10. int find(int n)
  11. {
  12.     if(Par[n] == n) return n;
  13.     else return Par[n] = find(Par[n]);
  14. }
  15.  
  16. void join(int a, int b)
  17. {
  18.     int ca = find(a), cb = find(b);
  19.     L[ca] = min(L[ca],L[cb]);
  20.     R[ca] = max(R[ca],R[cb]);
  21.     Par[cb] = ca;
  22. }
  23.  
  24. int main()
  25. {
  26.     cin >> N;
  27.     f(i,1,N) scanf("%d", &A[i].first);
  28.     f(i,1,N) A[i].second = i;
  29.     sort(A+1,A+N+1,greater<pair<int,int>>());
  30.  
  31.     f(i,1,N) L[i] = R[i] = i, Par[i] = i;
  32.     ll ans = 0;
  33.  
  34.     f(p,1,N)
  35.     {
  36.         int x = A[p].first, i = A[p].second;
  37.         if(In[i-1] && find(i-1) != find(i)) join(i-1,i);
  38.         if(In[i+1] && find(i+1 != find(i))) join(i+1,i);
  39.  
  40.         int c = find(i);
  41.         ll left = i - L[c] + 1;
  42.         ll right = R[c] - i + 1;
  43.         ans += left*right*x;
  44.  
  45.         In[i] = 1;
  46.     }
  47.  
  48.     cout << ans;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment