练习02 最高的奖励

Question

There are N tasks, each with a latest end time and corresponding reward. Complete this task before the end time and you will receive the reward. The time required to complete each task is 1 unit time. Sometimes it is impossible to complete all tasks, because there may be conflicts in time, which require you to choose. Seeking the highest reward you can get.

Standard

Input

Line 1 : A number N, indicating the number of tasks ( 2 ≤ \leq≤ N ≤ \leq≤ 50000)
Line 2 to N+1: two number per line, separated by spaces, indicating the latest end time E[i] of task and the corresponding reward W[i]. (1 ≤ \leq≤ E[i] ≤ \leq≤ 109)

Output

Output the Highest award available.

Sample

Input

7
4 20
2 60
4 70
3 40
1 30
4 50
6 10

Ouput

230

Analyse

首先,生成两个数组空间,对第一个数组输入数值,然后,要对第一个数组按照时间顺序排序,排序从小到大排序即可。之后要对时间相同的按价值进行排序,排序之后设立一个初试时间为1,开始遍历,如果第一个元素时间大于初始值,将这个元素放入第二个数组。如果时间小于最初设定的时间(之后还要对时间+1),则进行比较,找出最小,到了最后替换掉

Code

#include "iostream"
#include <algorithm> //接触的新的头文件,sort函数需要
#define N 50005
using namespace std;

struct high
{
	long long time;
	long long value;
};

bool compare(const high &left, const high &right)
{
	if (left.time < right.time)
	{
		return true;
	}
	else if ((left.time == right.time) && (left.value < right.value))
	{
		return true;
	}
	return false;
}  //从小到大排序
high award[N], award1[N];
int main()
{
	long long sum = 0;
	int num;
	cin >> num;

	for (int i = 1; i <= num; i++)
	{
		cin >> award[i].time >> award[i].value;
	}
	sort(award + 1, award + num + 1, compare);

	long tim = 1;
	award1[1] = award[1];
	sum += award1[1].value;
	for (int i = 2; i <= num; i++)
	{
		
		if (award[i].time > tim)//将第一个数组时间与初始时间比较,如果大于,将这个元素放入第二个数组
		{
			sum += award[i].value;
			award1[tim + 1] = award[i];
			tim++;
		}
		else if (award[i].time <= tim)  //时间小于初始,
		{
			long long temp = award1[1].value;   //初始化
			long flag = 1, j = 2;
			for (j; j <= tim; j++) 
			{
				if (award1[j].value < temp)     
				{
					temp = award1[j].value;   //之前认定的最小与找到的最新的最小交换
					flag = j;
				}
			}
			sum -= award1[flag].value;   //减去之前在sum内的第二个数组的价值
			award1[flag] = award[i];
			sum += award[i].value;    //求出总值

		}
	}
	cout << sum << endl;
    return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值