码迷,mamicode.com
首页 > 其他好文 > 详细

PaintHouse I

时间:2021-07-23 17:43:16      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:names   cos   ++   fine   class   cout   ace   dmi   continue   

ColorCostDP.hpp

//
// Created by Administrator on 2021/7/21.
//

#ifndef C__TEST01_COLORCOSTDP_HPP
#define C__TEST01_COLORCOSTDP_HPP

#include <vector>

class ColorCostDP {
public:
    ColorCostDP(vector<vector<int>> costN, int N);
    void printData();
    int algorithmDP(vector<vector<int>> &cost, int &N);
private:
    int N;                      // array of bulidings
    vector<vector<int>> cost;
};
ColorCostDP::ColorCostDP(vector<vector<int>> costN, int N):
        cost(costN), N(N)
{
    cost.resize(costN.size());
    for (int i = 0; i < costN.size(); ++i) {
        cost[i].resize(costN.size());
    }
}

void ColorCostDP::printData() {
    for(int i; i<cost.size();++i){
        for (int j = 0; j < cost[i].size(); ++j) {
            cout<<cost[i][j]<<" ";

        }
    }
}

int ColorCostDP::algorithmDP(vector<vector<int>> &cost, int &N){
    vector<vector<int>> f;
    f.resize(N+1); //f[1] is the first buliding
    for(int i = 0; i<f.size(); ++i)
        f[i].resize(3); //color of every buliding

    for(int i = 0; i<f.size(); ++i){
        if(i == 0) {
            f[0][0] = f[0][1] = f[0][2] = 0; //Initialization
            continue;
        }
        if(i == 1) {
            f[i][0] = cost[i-1][0];
            f[i][1] = cost[i-1][1];
            f[i][2] = cost[i-1][2]; //Initialization
            continue;
        }
        for(int j = 0; j < 3; ++j){
            f[i][j] = INT_MAX;
            for(int k = 0; k < 3; ++k){
                if(j == k) continue;
                if(f[i-1][k] + cost[i-1][j]<f[i][j])
                    f[i][j] = f[i-1][k] + cost[i-1][j];
            }
        }
    }
    int result = INT_MAX;
    for(int i = 0; i<3; i++){
        if(f[f.size()-1][i] < result)
            result = f[f.size()-1][i];
    }
    return result;
}

#endif //C__TEST01_COLORCOSTDP_HPP

main.cpp

#include <iostream>
using namespace std;

/*
 * 有一排N栋房子,每栋房子要漆成3种颜色中的一种:红蓝绿
任何相邻的两栋房子不能漆成同样的颜色
第i栋房子要染成红色、蓝色和绿色的花费分别为cost[i][0] cost[i][1] cost[i][2]
问最少花多少钱
 例子:
 输入:
 - N = 3
 - Cost = [[14, 2, 11], [11, 14, 5], [14, 3, 10]]
 -输出:10
 * */
#include "ColorCostDP.hpp"

int main() {
    vector<vector<int>> cost = {
            {14, 2, 11},
            {11, 14, 5},
            {14, 3, 10},
    };
    int N = 4;
    ColorCostDP ccdp(cost, N);

    //ccdp.printData();
    int result;
    result = ccdp.algorithmDP(cost, N);

    cout << result << endl;

    return 0;
}

PaintHouse I

标签:names   cos   ++   fine   class   cout   ace   dmi   continue   

原文地址:https://www.cnblogs.com/yoshinb/p/15047337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!