UVa系列——103/Stacking Boxes

引用请注明出处:http://blog.csdn.net/int64ago/article/details/7463401

这题的做法有点贪心的思想在里面,最后的处理也可以算是DP吧。根据贪心的思想,首先把每组从小到大排序,然后再根据字典序把按组排序,这样后面处理的时候会省很多处理,最后的DP有点像O(N*N)的最长递增子序列的实现。可能是为了好玩吧,第一次做题没有用c++和数组成分在里面(练习下指针大笑),所以用qsort不怎么熟悉,各组之间排序的时候用了一个小技巧,因为数据维度限制为10以下了,所以用double直接“哈希”了,最后0.008sAC的,个人觉得还能进一步优化的,但是算了吧,意义不大,刷版没意思。。。公司编译器不支持中文,注释就用了些英文。

#include  <stdio.h>
#include  <stdlib.h>
#include  <string.h>

int N, D;

struct cube{
	int *c;
	int seq;
	double sort_num;/*for the dimention of box is beside 10,there is a skill to sort boxes*/
};

/*
**sort each vector of boxes by increment
*/
int cmpD(const void *a, const void *b)
{
	return (*((int *)a) - *((int *)b));
}

/*
**sort boxes by increment
*/
int cmpN(const void *a, const void *b)
{
	if((((struct cube *)a)->sort_num - ((struct cube *)b)->sort_num) < 0)
		return -1;
	return 1;
}

/*
**define the compare-regular between boxes
*/
int is_nest(struct cube *a, struct cube *b)
{
	int i;
	for(i = 0; i < D; ++i){
		if(*(a->c + i) >= *(b->c + i))return 0;
	}
	return 1;
}


int main(int argc, char *argv[])
{
	while(scanf("%d%d", &N, &D ) != EOF){
	        struct cube *box = (struct cube*)malloc(sizeof(struct cube)*N);
		int i, j;
		for(i = 0; i < N; ++i){
		        (box + i)->c = (int *)malloc(sizeof(int)*D);
			for(j = 0; j < D; ++j)
				scanf("%d",((box + i)->c + j));
			qsort((box + i)->c, D, sizeof(int), cmpD);
			(box + i)->seq = i + 1;
			(box + i)->sort_num = 0;
			/*for sorting boxes*/
			for(j = 0; j < D; ++j){
				(box + i)->sort_num *= 10.0;
				(box + i)->sort_num += *((box + i)->c + j);
			}
		}
		qsort(box, N, sizeof(struct cube), cmpN);
		int *pre = (int *)malloc(sizeof(int)*N);
		int *nest_num = (int *)malloc(sizeof(int)*N);
		for(i = 0; i < N; ++i){
		    *(nest_num + i) = 1;
		    *(pre + i) = i;
                }
                /*get the final max nest-length and start position*/
		int gmax = 0, gk;
		for(i = N - 1; i >= 0; --i){
			int mmax = 0, k = i;/*get max nest-length and position of each loop*/
			for(j = i + 1; j < N; ++j)
				if(is_nest(box + i, box + j) && mmax <
						*(nest_num + j)){
					k = j;
					mmax = *(nest_num + j);
				}
			*(pre + i) = k;
			*(nest_num + i) += mmax;
			if(*(nest_num + i) > gmax){
				gmax = *(nest_num + i);
				gk = i;
			}
		}
		printf("%d\n", gmax);
		while(pre[gk] != gk){
			printf("%d ", (box + gk)->seq);
			gk = pre[gk];
		}/*here care the output format*/
		printf("%d\n", (box + gk)->seq);
		free(pre);
		free(nest_num);
		for(i = 0; i < N; ++i)
                        free((box + i)->c);
                free(box);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值