Codeforces 580B: Kefa and Company(尺取法)

来源:互联网 发布:java输出后buffered 编辑:程序博客网 时间:2024/04/29 08:36
B. Kefa and Company
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.

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 compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company 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 company to be maximum. Help him invite an optimal company!

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 misi(0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.

Output

Print the maximum total friendship factir that can be reached.

Examples
input
4 575 50 100150 2075 1
output
100
input
5 1000 711 3299 1046 887 54
output
111
Note

In the first sample test the most profitable strategy is to form a company 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.


题目大意:

主人公有n个朋友,这些朋友的属性有:与主人公的友情度,钱的多少。

给出了这些朋友的属性,为了避免聚会攀比造成不愉快,且使主人公高兴,先需要邀请其中的某些朋友,使这些朋友间的金钱差小于d,求能邀请的这些人,使得友情度之和最大。

解题思路:

将这些朋友们的金钱从小到大排序,从左往右扫描,左右边界随时变化,满足金钱差时,左端点不动,右端点向右扫描,如果不满足金钱差,则更新左端点,也更新ans。(尺取法,跟毛毛虫移动似得。。。)

代码如下:

#include <stdio.h>#include <algorithm>using namespace std;struct node{__int64 money,val;}per[100010];__int64 max(__int64 a,__int64 b){if(a>b)return a;elsereturn b;}bool cmp(struct node a,struct node b){return a.money<b.money;}int main(){__int64 n,d;scanf("%I64d%I64d",&n,&d);for(__int64 i=0;i<n;i++){scanf("%I64d%I64d",&per[i].money,&per[i].val);}sort(per,per+n,cmp);__int64 l=0,r=0,ans=0,sum=0;//初始化答案,左右端点 while(l<n&&r<n)//注意控制结束的条件 {while(r<n&&(per[r].money-per[l].money<d)){sum=sum+per[r].val;r++;//满足条件时向右扩张 }ans=max(ans,sum);//更新答案 sum=sum-per[l].val;//去掉左端点的值 l++;//更新左端点 }printf("%I64d\n",ans);return 0;}


0 0
原创粉丝点击