HDU 2037 dp 节目安排,怎么收看最多的完整节目

来源:互联网 发布:东莞唯一网络 编辑:程序博客网 时间:2024/06/11 17:24
说是动态规划,其实也有点贪心的思想。
一维数组里保存的的就是以当前节目作为开始,最多能完整地看多少个不同的节目。
很明显,播出时间最晚的节目只是能1。
我采取从后往前的规划方法。
这样,当循环到i时,能保证数组里 D[i+1] -> D[n-1] 保存的都是最优解。
所以让j 从 i+1 到 n-1 循环,找出看完第i个节目后最多还能看的节目数max。(不要忘了判断能否完整收看哦)

把max+1 保存到 D[i]里。如此下去直到结束。


#include <stdio.h>#include <stdlib.h>struct c{int x;int y;int ord;}d[100];int cmp(const void *a, const void *b){if ((*(struct c *)a).x == (*(struct c *)b).x)return (*(struct c *)a).y - (*(struct c *)b).y;elsereturn (*(struct c *)a).x - (*(struct c *)b).x;}int main(void){int i, j, n, max;while (scanf("%d", &n), n){for (max = i = 0; i < n; i++){scanf("%d%d", &d[i].x, &d[i].y);d[i].ord = 1;}qsort(d, n, sizeof(struct c), cmp);d[n-1].ord = 1;for (i = n - 2; i >= 0; i--){for (j = i + 1; j < n; j++){if (d[i].y <= d[j].x && d[i].ord < d[j].ord + 1)d[i].ord = d[j].ord + 1;}if (max < d[i].ord)max = d[i].ord;}printf("%d\n", max);}return 0;}


原创粉丝点击