B. Kefa and company
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs companypany.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn’t want any friend to feel poor companypared to somebody else in the companypany (Kefa doesn’t count). A friend feels poor if in the companypany there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the companypany to be maximum. Help him invite an optimal companypany!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, ) — the number of Kefa’s friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa’s friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Sample test(s)
input
4 5
75 5
0 100
150 20
75 1
output
100
input
5 100
0 7
11 32
99 10
46 8
87 54
output
111
Note
In the first sample test the most profitable strategy is to form a companypany from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
解题思路:
先用一个结构体数组存储m[i],s[i]
将结构体按m[i]大小进行排序
用f[i]存储1~i friend factor的总大小
将 j 从1开始算起判断company[i].m - company[j].m >= d,若成立j++
若不成立,break
将max与f[i]-f[j-1]比较大小
输出max
其中j最多使用n次
最坑的地方是要用long long 存储数据,否则会溢出,这个点让我到最后才想到,下次要注意!!
//
// main.cpp
// codend2
//
// Created by zhoujl on 15/9/23.
// Copyright (c) 2015年 zhoujl. All rights reserved.
//
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
long long max(long long a, long long b) {
if (a > b)
return a;
return b;
}
const int maxn = 100000+10;
struct Friend {
int m;
int s;
};
int cmp(Friend a, Friend b) {
return a.m < b.m;
}
long long f[maxn];
int main() {
int n, d;
long long max1 = 0;
Friend company[100010];
company[0].m = 0;
company[0].s = 0;
scanf("%d%d", &n, &d);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &company[i].m, &company[i].s);
}
int j = 1;
sort(&company[1], company+n+1, cmp);
f[0] = 0;
max1 = 0;
for (int i = 1; i <= n; i++) {
f[i] = f[i-1]+company[i].s;
max1 = max(company[i].s, max1);
while (company[i].m-company[j].m >= d) {
j++;
}
max1 = max(f[i]-f[j-1], max1);
}
printf("%I64d\n", max1);
return 0;
}