练习02 最高的奖励

练习02 #1163 最高的奖励

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;
}





猜你喜欢

转载自blog.csdn.net/deepdarkfan/article/details/88546328
今日推荐