这题的做法有点贪心的思想在里面,最后的处理也可以算是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; }