阿里编程题

给出N,K,N代表有N个方块,K代表K种颜色,N*K的矩阵代表第n块涂上第k种颜色的花费,要求找出花费最小的方案



输入:

4 3
2 3 2
9 1 4
7 8 1
2 8 3

输出:

6




#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <limits.h>
#include <cstring>
using namespace std;

/** 请完成下面这个函数,实现题目要求的功能 **/
 /** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^  **/
int minCost(vector<vector<int> >& costs)
{
	if(costs.empty()) return -1;
	int N = costs.size();
	int K = costs[0].size();
	
	int colors[N+1];
	int arr[N+1];//代表这个方块已经用过了。当时写的时候太慌了,原本考虑到了,但是后来忘了干嘛的。。把他给删了
	memset(colors,0,sizeof(colors));
	memset(arr,0,sizeof(arr));
	
	for(int i = 0; i < N; ++i){
		int min_cost=10000; 
		int min_color;
		int block=0;
		for(int j = 0; j < N; ++j){
			if(arr[j]) continue;
			for(int l = 0; l < K; ++l){
				if(costs[j][l]<min_cost){
					bool flag=false;
					if(j==0&&(colors[j+1]==0||colors[j+1]!=l+1)){
						flag=true;
					}
					else{
						flag=false;
					}
					if(j==N-1&&(colors[j-1]==0||colors[j-1]!=l+1)){
						flag=true;
					}
					else{
						if((colors[j+1]==0||colors[j+1]!=l+1)&&(colors[j-1]==0||colors[j-1]!=l+1)){
							flag=true;
						}
						else flag=false;
					}
					
					if(flag){
						min_color = l+1;
						block = j;
						min_cost = costs[j][l];
					}	
				}
			}
			colors[block]=min_color; 
			arr[block]=1;
		}
		
	}
	int res=0;
	for(int i=0; i < N; ++i){
		res+=costs[i][colors[i]-1];
	}
	return res;
}

int main()
{
	int N,K;
	int cost;
	vector<vector<int> > costs;
	string s;
	istringstream is;

	getline(cin, s);
	is.str(s);
	is>>N>>K;
	for(int i =0 ; i < N; i++)
	{
		vector<int> t;
		getline(cin, s);
		is.clear();
		is.str(s);
		for(int j = 0; j < K; j++) {
			is >> cost;
			t.push_back(cost);
		}
		costs.push_back(t);
	}
	cout<<minCost(costs)<<endl;
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值