uva 103 Stacking Boxes

递归式的动态规划,很有意思

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <set>
using namespace std;

typedef int BOX_SIZE;
typedef int BOX_INDEX;
vector< vector<BOX_SIZE> > v;
vector< vector<BOX_INDEX> > path;
set<int> visited;

int box_n_g;


bool is_bigger(int box1, int box2){
	int i; bool res;
	res = true;
	for(i=0; i<v[box1].size(); i++){
		if(v[box1][i] <= v[box2][i]){
			res = false;
			break;
		}
	}
	return res;
}


//dp[cur]是以第cur个盒子作为最大的盒子的情况下,最多可以有多少个盒子符合要求
int get_dp(int cur, int *dp, vector< vector<BOX_INDEX> > &path){
	int i, temp;

	if(visited.find(cur) != visited.end())
		return dp[cur];
	
	visited.insert(cur);
	for(i=1; i<=box_n_g; i++){
		if(cur == i)
			continue;

		if(is_bigger(cur, i)){
			temp = get_dp(i, dp, path) + 1;
			if(dp[cur] < temp){
				dp[cur] = temp;
				path[cur] = path[i];
				path[cur].push_back(cur);
			}
		}
	}
	return dp[cur];
}


void func(int box_n){
	int *dp;
	int i, max, cur_dp, max_i;
	vector<BOX_INDEX> vv;

	dp = (int*)malloc(sizeof(int)*(box_n+1));
	path.clear();
	path.push_back(vv);
	for(i=1; i<=box_n; i++){
		dp[i] = 1;
		vv.clear();
		vv.push_back(i);
		path.push_back(vv);
	}
	visited.clear();
	max = -1;
	max_i = -1;
	for(i=1; i<=box_n; i++){
		cur_dp = get_dp(i, dp, path);
		if(max < cur_dp){
			max = cur_dp;
			max_i = i;
		}
	}
	free(dp);

	printf("%d\n", max);
	for(i=0; i<path[max_i].size(); i++){
		if(i > 0)
			printf(" ");
		printf("%d", path[max_i][i]);
	}
	printf("\n");
}

int main(void){
	int box_n, weidu_n, i, j, size;
	vector<BOX_SIZE> vv;

	//freopen("input.dat", "r", stdin);
	while(scanf("%d %d", &box_n, &weidu_n) != EOF){
		box_n_g = box_n;
		v.clear();
		v.push_back(vv);
		for(i=1; i<=box_n; i++){
			vv.clear();
			for(j=0; j<weidu_n; j++){
				scanf("%d", &size);
				vv.push_back(size);
			}
			sort(vv.begin(), vv.end());
			v.push_back(vv);
		}
		func(box_n);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值