admin管理员组

文章数量:1648299

这是一道比较经典的贪心算法题。

原题目如下:

Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.

Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.

All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.

Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.

Input

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 00), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.

The second line contains n integers c1, c2, …, cn (1 ≤ ci ≤ 10^5), here ci is the cost of delaying the i-th flight for one minute.

Output

The minimum possible total cost of delaying the flights.

Example

Input

5 2
4 2 1 10 2

Output

20

 

题目大意:

机场原本有n架飞机在n分钟内有序起飞,每分钟有且只有一架飞机起飞。但现在机场规定前k分钟所有飞机都不能起飞,则所有飞机的起飞时刻往后推延,但是可以调整起飞顺序(规定调整后飞机的起飞时刻不能比原来的起飞时刻早)每架飞机都有其延迟代价,现在要求调整飞机的起飞顺序以得到所有飞机的延迟代价加起来的最小值。

 

思路:

本题是一道典型的贪心算法题。我们知道一架飞机的延迟代价=该飞机的延迟代价 *(调整后的起飞时刻 - 原起飞时刻)

显然,调整后的起飞时刻差越小,延迟代价越小,当不改变飞机的起飞时刻时,这架飞机的代价为0。

所以要求所有飞机的最小代价,就按延迟代价从大到小把飞机调整到最接近原起飞时刻的位置即可。
 

代码如下:

#include<iostream>
#include<queue>

using namespace std;

struct Node{
	long long j, m;
	bool operator < (const Node &a) const{
		return (m == a.m ? j > a.j : m < a.m);
	}
	Node(long long j, long long m) : j(j), m(m){
	};
};

priority_queue<Node> q;

int main() {
	long long n, k, temp, ans = 0;
	Node max(0,0);
	cin >> n >> k;
	
	for(int i = 1; i<=n+k; i++) {
		if (i <= n) {
			cin >> temp;
			q.push(Node(i, temp));
		}
		if(i > k) {
			max = q.top();
			ans += max.m * (i - max.j);
			q.pop();
		}
	}
	
	cout << ans << endl;
	return 0;
} 

 

本文标签: 算法贪心Planning