Advertisement
imashutosh51

Paint House II

Nov 8th, 2022
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. /*
  2. Logic:
  3. Logic is same as paint house 1 but we need minimum from previous row but we can get the first and second minimum
  4. because if the minimum cost is of different color then cost to color is current_cost+previous min
  5.         else current_cost+second_previous_min;
  6. */
  7. #include <iostream>
  8. #include <bits/stdc++.h>
  9. using namespace std ;
  10. int main()
  11. {
  12.   int n ;
  13.   cin >> n ;
  14.   int k ;
  15.   cin >> k ;
  16.   vector<vector<int>>  arr(n, vector<int>(k, 0));
  17.   for (int i = 0 ; i < arr.size() ; i++)
  18.   {
  19.     for (int j = 0 ; j < arr[0].size() ; j++)
  20.     {
  21.       cin >> arr[i][j] ;
  22.     }
  23.   }
  24.  
  25.   // min values ;
  26.   int min = INT_MAX;
  27.   int smin = INT_MAX;
  28.   //get min and second min from first column
  29.   for (int j = 0; j < arr[0].size(); j++) {
  30.     if (arr[0][j] <= min) {
  31.       smin = min;
  32.       min = arr[0][j];
  33.     } else if (arr[0][j] <= smin) {
  34.       smin = arr[0][j];
  35.     }
  36.   }
  37.   // get answer
  38.   for (int i = 1; i < arr.size(); i++) {
  39.     int cmin = INT_MAX;
  40.     int csmin = INT_MAX;
  41.  
  42.     for (int j = 0; j < arr[i].size(); j++) {
  43.       if (arr[i - 1][j] != min) {
  44.         arr[i][j] += min;
  45.       } else {
  46.         arr[i][j] += smin;
  47.       }
  48.  
  49.       if (arr[i][j] <= cmin) {
  50.         csmin = cmin;
  51.         cmin = arr[i][j];
  52.       } else if (arr[i][j] <= csmin) {
  53.         csmin = arr[i][j];
  54.       }
  55.     }
  56.  
  57.     min = cmin;
  58.     smin = csmin;
  59.   }
  60.  
  61.   c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement