关闭

最小重量机器设计问题

109人阅读 评论(0) 收藏 举报
分类:

input.txt

3 3 4
3 2 1
1 2 3
1 2 2
1 2 3
3 2 1
2 2 2


#include <iostream>
#include <fstream>
using namespace std;



int main(){
	//读取文件
	ifstream in("input.txt", ios::in);
	if (!in.is_open()){
		cout << "Error opening file";
		exit(1);
	}
	int n = in.get() - '0';
	in.get();
	int m = in.get() - '0';
	in.get();
	int d = in.get() - '0';
	in.get();
	int** c = new int*[n];
	for (int i = 0; i < n; i++){
		c[i] = new int[m];
	}
	int** w = new int*[n];
	for (int i = 0; i < n; i++){
		w[i] = new int[m];
	}
	for (int i = 0; i < 2 * n; i++){
		if (i < n){
			for (int j = 0; j < m; j++){
				c[i][j] = in.get() - '0';
				in.get();
			}
		}
		else if ((i < 2 * n) && (i >= n)){
			for (int j = 0; j < m; j++){
				w[i-3][j] = in.get() - '0';
				in.get();
			}
		}
	}
	cout << n << " " << m << " " << d << endl;
	for (int i = 0; i < n; i++){
		cout << c[i][0] << " " << c[i][1] << " " << c[i][2] << endl;
		cout << w[i][0] << " " << w[i][1] << " " << w[i][2] << endl;
	}
	//读取文件完毕
	//数据处理
	//已初始化数据n,m,d,c[][],w[][]
	bool flag = true;
	int ci = 0;//当前层
	int* bestx = new int[n];//记录最佳序列
	int* x = new int[n];//记录当前序列
	int bestw = INT_MAX;//最小重量
	int nc = 0;//当前价值
	int nw = 0;//当前重量
	int j = 0;//第一个
	int* min = new int[n];
	min[n - 1] = 0;
	int r = 0;
	for (int i = n-1; i >0; i--){
		r = w[i][0];
		for (int j = 1; j < m; j++){
			if (w[i][j] < r){
				r = w[i][j];
			}
		}
		min[i-1] = r+min[i];
	
	}
	
	while (flag){
		while ((ci < n) && (nc < d)){//向左走(上界)
			nc += c[ci][j];
			nw += w[ci][j];
			x[ci] = j;
			ci++; 
			if (ci != n){//到叶子就不跑左子树
				j = 0;
			}
			
		}
		if ((ci == n)&&(nc<=d)){//到叶子
			if (nw < bestw){
				bestw = nw;
				for (int z = 0; z < n; z++){
					bestx[z] = x[z];
				}
			}
		}
		//减去多余
		ci--;
		nc -= c[ci][x[ci]];
		nw -= w[ci][x[ci]];
		j = x[ci];
		do{//移动当前层的下一个节点
			j++;
		} while ((j < m) && (nc + c[ci][j]>d) );//判断下一个节点是否可用

		while ((bestw != 0) && (nw + min[ci] + w[ci][j] >= bestw)&&(j<m)){//判断有没有必要移动到下一个节点(下界)
			j++;
		}

		while (j == m){//当该层跑完回溯上层直到有一层还没遍历完的
			ci--;
			if (ci == -1){
				flag = false;
				break;
			}
			nc -= c[ci][x[ci]];
			nw -= w[ci][x[ci]];
			j = x[ci] + 1;
		}

		

	}
	cout << "最小重量" << bestw << endl;
	for (int i = 0; i < n; i++){
		cout << " " << 1+bestx[i];
	}
	cout << endl;
	return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7447次
    • 积分:346
    • 等级:
    • 排名:千里之外
    • 原创:28篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条