-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_516_PaintHouseII.cpp
More file actions
60 lines (44 loc) · 1.49 KB
/
Copy path_516_PaintHouseII.cpp
File metadata and controls
60 lines (44 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* Source - https://www.lintcode.com/problem/paint-house-ii/description/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
int minCostII(vector<vector<int>> &costs) {
if (costs.size() == 0)
return 0;
int n = costs.size();
int k = (n == 0) ? 0 : costs[0].size();
vector<int> dp(k);
int firstmin, secondmin;
for (int i = 0; i < n; i++) {
int prefmin = (i == 0) ? 0 : firstmin, presmin = (i == 0) ? 0 : secondmin;
firstmin = INT_MAX, secondmin = INT_MAX;
for (int j = 0; j < k; j++) {
if (dp[j] != prefmin || prefmin == presmin)
dp[j] = costs[i][j] + prefmin;
else dp[j] = costs[i][j] + presmin;
if (firstmin <= dp[j])
secondmin = min(secondmin, dp[j]);
else {
secondmin = firstmin;
firstmin = dp[j];
}
}
}
return firstmin;
}
int main()
{
int n, k;
cout<<"Enter number of houses: ";
cin>>n;
cout<<"Enter number of colors: ";
cin>>k;
vector<vector<int>> costs(n, vector<int> (k));
cout<<"Enter costs row-wise: "<<endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++)
cin>>costs[i][j];
}
cout<<"Minimum cost to paint the houses with k colors such that no two consecutive houses have same color: "<<minCostII(costs)<<endl;
}