粉刷匠的难题
题目描述
粉刷匠遇到了一个难题:有n根柱子排成一条直线,需要给柱子涂上颜色,现在共有k种颜色,每根柱子涂不同颜色的费用不同。并且要求相邻柱子颜色不同。你能帮他计算最小的支出费用吗?
费用通过一个n*k 的矩阵给出,比如cost[0][0]表示柱子0涂颜色0的费用,cost[1][2]表示柱子1涂颜色2的费用。
测试输入:
3 3
14 2 11
11 14 5
14 3 10
预期输出:
10
解题思路
这个题很明显是从每一行的数中选择一个使得加和最小。而且相邻的行不能选择同一个列。可以用dfs递归,找到所有的情况,然后从中找到最小的那个结果。
代码如下
#include<cstdio>
int n,k;
int min = 1e9;
int cost[100][100];
void dfs(int x,int y,int cnt){
if(x == n){
if(cnt < min){
min = cnt;
}
return;
}
for(int i = 0; i< k; i++){
if(i == y) continue;
else{
cnt += cost[x][i];
dfs(x+1,i,cnt);
cnt -= cost[x][i];
}
}
}
int main(){
scanf("%d%d",&n,&k);
for(int i = 0; i<n; i++)
for(int j = 0; j<k; j++)
scanf("%d",&cost[i][j]);
for(int i = 0; i<k; i++){
dfs(1,i,cost[0][i]);
}
printf("%d",min);
}