Ritam_C

Trapping Rainwater

May 13th, 2021 (edited)
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. typedef long long ll;
  3. typedef unsigned long long ull;
  4. typedef long double ld;
  5. #define vi vector<int>
  6. #define vll vector<long long>
  7. #define pb push_back
  8. #define vpll vector<pair<ll, ll>>
  9. #define vpi vector<pair<int, int>>
  10. #define p_b pop_back
  11. #define FOR(a, b) for(int i = a; i <= b; i++)
  12. #define tests() int t; cin >> t; while(t--)
  13. #define input(a, n) for(int i = 0; i < n; i++){int x; cin >> x; a.pb(x);}
  14. #define MOD (ull)1000000007
  15. using namespace std;
  16.  
  17. ll trappingWater(int arr[], int n){
  18.     int i = 0, k = 0;
  19.     ll sum = 0;
  20.     bool f = true;
  21.     while(i < n){
  22.         int j = i;
  23.         //check for values in the array after i which are less than or equal to arr[i]
  24.         while(arr[j] <= arr[i] && j < n){
  25.             j++;
  26.         }
  27.         /*if the loop reaches the end of the array then it means that the last element of the array
  28.         is less than arr[i], hence the we should calculate in the reverse order upto i to find the sum,
  29.         if its not the case then simply calculate the differences with arr[i] and we will get the total volume*/
  30.         if(j == n){
  31.             f = false;
  32.             k = i;
  33.             break;
  34.         } else{
  35.             int tmp = j;
  36.             j--; //decremented due to fact that arr[j] is greater than arr[i]
  37.             while(j >= i){
  38.                 sum += arr[i]-arr[j];
  39.                 j--;
  40.             }
  41.             i = tmp;
  42.         }
  43.     }
  44.     if(!f){
  45.         /*if the first case is satisfied in the earlier loop then find the differences from the back of the array*/
  46.         i = n-1;
  47.         while(i >= k){
  48.             int j = i;
  49.             while(arr[j] <= arr[i] && j >= k){
  50.                 sum += arr[i]-arr[j];
  51.                 j--;
  52.             }
  53.             i = j;
  54.         }
  55.     }
  56.     return sum;
  57. }
  58.  
  59. int main(){
  60.     ios_base::sync_with_stdio(false);
  61.     cin.tie(NULL);
  62.     int n;
  63.     cin >> n;
  64.     int arr[n];
  65.     for(int i = 0; i < n; i++){
  66.         cin >> arr[i];
  67.     }
  68.     cout << trappingWater(arr, n);
  69.     return 0;
  70. }
Add Comment
Please, Sign In to add comment