Advertisement
lifeiteng

Painting with minimum cost

Sep 20th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1.     int minCostPaintAtMostTwoSameColor(int[][] cost)
  2.     {
  3.         // cost in form n x 3
  4.         // cost[0][1] = paint house 0 with color 1
  5.         int n = cost.length, inf = Integer.MAX_VALUE;
  6.         // f[i][j] = minimum cost to paint up to i houses ending with paint j
  7.         int[][] f = new int[n + 1][3];
  8.         f[1] = cost[0];
  9.         for(int j = 0; j < 3; j++)
  10.             f[2][j] = Math.min(f[1][0], Math.min(f[1][1], f[1][2])) + cost[1][j];
  11.         for(int i = 2; i < n; i++)
  12.         {
  13.             // loop through colors
  14.             for(int j = 0; j < 3; j++)
  15.             {
  16.                 int diffColor = inf, sameColor = inf;
  17.                 for(int k = 0; j < 3; k++)
  18.                 {
  19.                     if(j == k) continue;
  20.                     diffColor = Math.min(diffColor, f[i][k]);
  21.                     sameColor = Math.min(sameColor, f[i - 1][k] + cost[i][j]);
  22.                 }
  23.                 f[i + 1][j] = Math.min(diffColor, sameColor);
  24.             }
  25.         }
  26.         return Math.min(Math.min(f[n][0], f[n][1]), f[n][2]);
  27.     }
  28.    
  29.     int minCostPaintNoSameColor(int[][] cost)
  30.     {
  31.         int n = cost.length, inf = Integer.MAX_VALUE;
  32.         int[][] f = new int[n + 1][3];
  33.         for(int i = 0; i < n; i++)
  34.         {
  35.             f[i + 1][0] = Math.min(f[i][1], f[i][2]) + cost[i][0];
  36.             f[i + 1][1] = Math.min(f[i][0], f[i][2]) + cost[i][1];
  37.             f[i + 1][2] = Math.min(f[i][0], f[i][1]) + cost[i][2];
  38.         }
  39.         return Math.min(Math.min(f[n][0], f[n][1]), f[n][2]);
  40.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement