矩形嵌套
时间限制:3000 ms | 内存限制:65535 KB
难度:4
- 描述
- 有n个矩形,每个矩形可以用a,b来描述,表示长和宽。矩形X(a,b)可以嵌套在矩形Y(c,d)中当且仅当 a<c,b<d或者b<c,a<d(相当于旋转X90度)。例如(1,5)可以嵌套在(6,2)内,但不能嵌套在(3,4)中。 你的任务是选出尽可能多的矩形排成一行,使得除最后一个外,每一个矩形都可以嵌套在下一个矩形内。
- 输入
- 第一行是一个正正数N(0<N<10),表示测试数据组数,
每组测试数据的第一行是一个正正数n,表示该组测试数据中含有矩形的个数(n<=1000)
随后的n行,每行有两个数a,b(0<a,b<100),表示矩形的长和宽 - 输出
- 每组测试数据都输出一个数,表示最多符合条件的矩形数目,每组输出占一行
- 样例输入
-
1 10 1 2 2 4 5 8 6 10 7 9 3 1 5 8 12 10 9 7 2 2
- 样例输出
-
5
//C v0.1 AC #include<stdio.h> #include <stdlib.h> #include <string.h> #include <alloca.h> struct rectangle { int length; int width; } rctg[1000]; int dplis(struct rectangle rctg[], int n); //order by length asc ,or order by width asc int compare(const void *a, const void *b) { struct rectangle *rct1 = (struct rectangle *)a; struct rectangle *rct2 = (struct rectangle *)b; if (rct1->length == rct2->length) return (rct1->width - rct2->width); return (rct1->length - rct2->length); } int main(void) { int i; int n; scanf("%d", &n); getchar(); while (n--) { int m; scanf("%d", &m); getchar(); memset(&rctg, 0x00, sizeof(rctg)); for (i = 0; i < m; i++) { scanf("%d%d", &rctg[i].length, &rctg[i].width); if (rctg[i].length < rctg[i].width) { int tmp; tmp = rctg[i].length; rctg[i].length = rctg[i].width; rctg[i].width = tmp; } } qsort(rctg, m, sizeof(rctg[0]), compare); int rctgmax = dplis(rctg, m); printf("%d\n", rctgmax); } return 0; } int dplis(struct rectangle rctg[], int n) { int *d = (int *)alloca(sizeof(int) * (n)); int len = 1; int i; int j; for (i = 0; i < n; ++i) { d[i] = 1; for (j = 0; j < i; ++j) { if (rctg[j].width < rctg[i].width && rctg[j].length < rctg[i].length && d[j] + 1 > d[i]) { d[i] = d[j] + 1; } } if (d[i] > len) { len = d[i]; } } return len; }
//C v0.1 WA! #include<stdio.h> #include <stdlib.h> #include <string.h> struct rectangle { int length; int width; } rctg[1000]; //order by length asc ,or order by width asc int compare(const void *a, const void *b) { struct rectangle *rct1 = (struct rectangle *)a; struct rectangle *rct2 = (struct rectangle *)b; if (rct1->length == rct2->length) return (rct1->width - rct2->width); return (rct1->length - rct2->length); } int main(void) { int i; int n; scanf("%d", &n); getchar(); while (n--) { int m; scanf("%d", &m); getchar(); memset(&rctg, 0x00, sizeof(rctg)); for (i = 0; i < m; i++) { scanf("%d%d", &rctg[i].length, &rctg[i].width); if (rctg[i].length < rctg[i].width) { int tmp; tmp = rctg[i].length; rctg[i].length = rctg[i].width; rctg[i].width = tmp; } } qsort(rctg, m, sizeof(rctg[0]), compare); printf("after asc sort\n"); for (i = 1; i < m; i++) { printf("%d %d\n", rctg[i].length, rctg[i].width); } int sum = 1; int idx = 0; for (i = 1; i < m; i++) { //printf("%d %d\n", rctg[i].length, rctg[i].width); if (rctg[idx].length < rctg[i].length && rctg[idx].width < rctg[i].width) { ++sum; idx = i; } else { continue; } } printf("%d\n", sum); } return 0; }