Exercise 02 The highest reward

Exercise 02 #1163 The highest reward

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

output

230

Analyse

First, generate two array spaces, enter values ​​for the first array, and then sort the first array in chronological order, from small to large. After that, sort by value with the same time. After sorting, set an initial test time of 1 and start traversing. If the time of the first element is greater than the initial value, put this element into the second array. If the time is less than the initially set time (the time will be +1 later), then compare, find the smallest, and replace it at the end

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





Guess you like

Origin blog.csdn.net/deepdarkfan/article/details/88546328