Description
A postman delivers letters to his neighbors in a one-dimensional world.
The post office, which contains all of the letters to begin with, is located at
x=0
, and there are
n
houses to which the postman needs to deliver the letters. House
The postman must start at the post office, pick up some number of letters less than or equal to his carrying capacity, and then travel to some of the houses dropping off letters. He must then return to the post office, repeating this process until all letters are delivered. At the end he must return to the post office.
The postman can travel one unit of distance in one unit of time.
What is the minimum amount of time it will take the postman to start at the post office, deliver all the letters, and return to the post office?
Translation
一个邮递员给一个一维世界里的邻居派送邮件。
邮局在
Input
The first line of input contains two space-separated integers
Each of the next n lines contains two space-separated integers
xi(|xi|≤107)
and
mi(1≤mi≤107)
.
Output
Print, on a single line, the minimum amount of time it will take to complete the mail delivery route
Sample 1
Sample Input
4 10
-7 5
-2 3
5 7
9 5
Sample Output
42
Sample 2
Sample Input
7 1
9400000 10000000
9500000 10000000
9600000 10000000
9700000 10000000
9800000 10000000
9900000 10000000
10000000 10000000
Sample Output
1358000000000000
Solution
贪心:显然是先往远的送,因为送多了回来的时候就可以顺路给路过的地方。如果一边送完了还有多的也重新送,因为反正肯定要路过邮局才会到另一边运,顺便重新带k封邮件是没有问题的。
Code
#include <cstdio>
#include <algorithm>
using namespace std;
#define st first
#define nd second
typedef long long ll;
pair<int, int> p[1005];
int deliver(int &d, int i, int k) {
if (p[i].nd <= d)
d -= p[i].nd;
else {
p[i].nd -= d;
ans += (1ll * p[i].nd / k + (p[i].nd % k != 0)) * (2ll * llabs(p[i].first));
if (p[i].nd % k != 0)
d = k - p[i].nd % k;
else
d = 0;
}
}
int main() {
ll d, ans = 0;
int n, k, i;
scanf("%d%d", &n, &k);
for (i = 1; i <= n; ++ i)
scanf("%d%d", &p[i].st, &p[i].nd);
sort(p + 1, p + n + 1);
for (d = 0, i = 1; p[i].st < 0; ++ i)
deliver(d, i, k);
for (d = 0, i = n; p[i].st > 0; -- i)
deliver(d, i, k);
printf("%I64d\n", ans);
return 0;
}