九度 1499:项目安排 (一维DP)

题目描述

总结

1. 和 Leetcode Palindrome cut 的设置方法类似

2. 时间复杂度为 o(n^2), n 为任务个数

3. 为了优化空间复杂度(同时也优化时间复杂度), dp[i] 表示第 i 个任务的开始时间到 endTime 之间能够获得的最大收益

代码

/*
 * source.cpp
 *
 *  Created on: 2014-4-4
 *      Author: vincent
 */
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <memory.h>
using namespace std;

/*
 * dp[i] ~ time[i-endtime] 能够获得的最大收益
 * dp[i] = dp[j] + job[].money
 * 优化, 把时间 i 替换成第 i 个任务的开始时间
 * 这道题和 palindrome cut 类似
 */

class Job {
public:
	int money;
	int st, ed;
	Job(int _st, int _ed, int _money):st(_st), ed(_ed), money(_money) {
	}
	Job() {
		Job(0, 0, 0);
	}
	bool operator <(const Job &other) const {
		return this->st < other.st;
	}
};

Job jobs[10010];
int dp[10010];

int cal(int n) {
	memset(dp, 0, sizeof(dp));
	dp[n-1] = jobs[n-1].money;
	for(int i = n-2; i >= 0; i --) {
		int j = i+1;
		while(j < n && jobs[j].st < jobs[i].ed)
			j++;
		dp[i] = max(dp[i+1], jobs[i].money+dp[j]);
	}
	return dp[0];
}

int main() {
	freopen("input.txt", "r", stdin);
	int n;
	while(scanf("%d", &n) != EOF) {
		for(int i = 0; i < n; i ++) {
			int st, ed, money;
			scanf("%d%d%d", &st, &ed, &money);
			jobs[i].st = st; jobs[i].ed = ed, jobs[i].money = money;
		}
		sort(jobs, jobs+n);

		int res = cal(n);
		printf("%d
", res);
	}

	return 0;
}

  

原文地址:https://www.cnblogs.com/zhouzhuo/p/3646367.html