uva 10131 Is Bigger Smarter?

简单的动态规划

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

struct node{
	int id;
	int weight;
	int zhishang;
};

vector<struct node> v;


struct dp_node{
	int len;
	int pre_index; //前一个节点的下标
};

struct dp_node dp[1005];

int cmp_weight_ins(const void *a, const void *b){
	struct node *pa = (struct node*)a;
	struct node *pb = (struct node*)b;
	
	if(pa->zhishang > pb->zhishang)
		return -1;
	else if(pa->zhishang < pb->zhishang)
		return 1;
	else{
		if(pa->weight > pb->weight)
			return 1;
		else if(pa->weight < pb->weight)
			return -1;
		else
			return 0;
	}
}

void func(){
	int len, i, j, max_len;
	len = v.size();
	int max_len_global;
	int choice_index, pre_i;

	if(0 == v.size()){
		printf("0\n");
		return;
	}

	qsort(&(v[0]), len, sizeof(struct node), cmp_weight_ins);

	dp[0].len = 1;
	dp[0].pre_index = -1;


	max_len_global = dp[0].len;
	choice_index = 0;
	for(i=1; i<=len-1; i++){
		max_len = 1;
		dp[i].len = 1;
		dp[i].pre_index = -1;

		for(j=i-1; j>=0; j--){
			if(j+2 <= max_len)
				break;
			if(v[i].weight > v[j].weight && v[i].zhishang < v[j].zhishang){
				if(max_len < dp[j].len+1){
					max_len = dp[j].len+1;
					dp[i].pre_index = j;
					dp[i].len = max_len;
				}
			}
		}
		if(dp[i].len > max_len_global){
			max_len_global = dp[i].len;
			choice_index = i;
		}
	}

	stack<int> s;

	printf("%d\n", dp[choice_index].len);
	s.push(v[choice_index].id);
	pre_i = choice_index;
	for(i=1; i<dp[choice_index].len; i++){
		pre_i = dp[pre_i].pre_index;
		s.push(v[pre_i].id);
	}

	while(!s.empty()){
		printf("%d\n", s.top());
		s.pop();
	}
}

int main(void){
	int w, z, count;
	struct node node_ins;


	//freopen("input.dat", "r", stdin);

	count = 1;
	while(scanf("%d %d", &w, &z) != EOF){
		node_ins.id = count++;
		node_ins.weight = w;
		node_ins.zhishang = z;
		v.push_back(node_ins);
	}
	func();
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值