Guest User

Untitled

a guest
May 23rd, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  3. #define F first
  4. #define S second
  5. #define PB push_back
  6. #define MP make_pair
  7. #define REP(i,a,b) for (int i = a; i <= b; i++)
  8.  
  9.  
  10. using namespace std;
  11.  
  12. typedef long long ll;
  13. typedef vector<int> vi;
  14. typedef pair<int,int> pi;
  15.  
  16. int main()
  17. {
  18.     fast;
  19.     int test;
  20.     cin>>test;
  21.     while(test--)
  22.     {
  23.         int n;
  24.         cin>>n;
  25.         //Input array for Length of bars at i'th block
  26.         int a[n];
  27.         for(int i =0;i<n;++i)
  28.         {
  29.             cin>>a[i];
  30.         }
  31.  
  32.         int max_ahead =0;
  33.         // for every i, we store the maximum bar ahead of i in this array
  34.         int ahead[n];
  35.         for(int i =n-1;i>=0;--i)
  36.         {
  37.             //is current max smaller than a[i]? if yes then a[i] is new max
  38.             max_ahead =max(max_ahead,a[i]);
  39.  
  40.             //store info
  41.             ahead[i]=max_ahead;
  42.         }
  43.         int ans =0;
  44.         int max_so_far =0;
  45.         for(int i =0;i<n;i++)
  46.         {
  47.             // in this variable we have maximum length of wall upto i
  48.             max_so_far = max(max_so_far,a[i]);
  49.  
  50.  
  51.             // water at i'th block will be min(max height upto i and max height ahead of i)
  52.             // if there's is a wall at i'th block, we will need to subtract that amount as it has consumed the area available for water
  53.             // NOTE: It is easy to see that this number will be non-negative
  54.             int water_at_i = min(max_so_far,ahead[i]) - a[i];
  55.  
  56.             // add the result
  57.             ans+=water_at_i;
  58.         }
  59.         //print the result
  60.         cout<<ans<<endl;
  61.     }
  62.     return 0;
  63.  
  64. }
Add Comment
Please, Sign In to add comment