Advertisement
IlidanBabyRage

waterfill.cpp

May 30th, 2015
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main(){
  6.    
  7.     int n;
  8.     cin >> n;
  9.     int *ar = new int[n];
  10.  
  11.     for (int i = 0; i < n; i++)
  12.         cin >> ar[i];
  13.  
  14.     int ileft = 0, iright = 0, left, right, tmph, total = 0, imax;
  15.  
  16.     while (ileft < n){
  17.         tmph = -1;
  18.         while (ileft < n - 1 && ar[ileft + 1] >= ar[ileft])
  19.             ileft++;
  20.         if (ileft >= n - 1)
  21.             break;
  22.         iright = ileft;
  23.         while (iright < n && ar[ileft] > ar[++iright]){
  24.             if (ar[iright] >= tmph){
  25.                 tmph = ar[iright];
  26.                 imax = iright;
  27.             }
  28.         };
  29.         if (iright < n && ar[iright] >= ar[ileft]){
  30.             for (int i = ileft; i < iright; i++){
  31.                 total += ar[ileft] - ar[i];
  32.             }
  33.             ileft = iright;
  34.             continue;
  35.         }
  36.         if (iright >= n){
  37.             ar[ileft] = tmph;
  38.         }
  39.         for (int i = ileft; i < imax; i++){
  40.             total += ar[ileft] - ar[i];
  41.         }
  42.         ileft = imax;
  43.     }
  44.  
  45.     cout << total << endl;
  46.  
  47.     delete [] ar;
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement