UVALive 7960|Gym 101201I|Postman|贪心

来源:互联网 发布:知之深爱之初 编辑:程序博客网 时间:2024/06/14 05:22

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 i is located at position xi, and there are mi letters that need to be delivered to this location. But the postman can only carry k letters at once.
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

一个邮递员给一个一维世界里的邻居派送邮件。
邮局在x=0处,一开始有所有要分发的邮件。邮递员需要派送邮件给n间屋子。第i间屋子在x=xi处,有mi封邮件待收。但是邮递员一次最多带k封邮件。邮递员一开始必须从邮局出发,带不超过k封邮件,到一些屋子投递。然后就要返回邮局。问邮递员最少走多长的路就可以分发完所有的邮件并回到邮局?

Input

The first line of input contains two space-separated integers n(1n1,000) and k(1k107).
Each of the next n lines contains two space-separated integers xi(|xi|107) and mi(1mi107).

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 35 79 5

Sample Output

42

Sample 2

Sample Input

7 19400000 100000009500000 100000009600000 100000009700000 100000009800000 100000009900000 1000000010000000 10000000

Sample Output

1358000000000000

Solution

贪心:显然是先往远的送,因为送多了回来的时候就可以顺路给路过的地方。如果一边送完了还有多的也重新送,因为反正肯定要路过邮局才会到另一边运,顺便重新带k封邮件是没有问题的。

Code

#include <cstdio>#include <algorithm>using namespace std;#define st first#define nd secondtypedef 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;}
原创粉丝点击