@xunuo
2017-02-22T16:49:14.000000Z
字数 2494
阅读 976
time limit per test 2 seconds memory limit per test256 megabytes
结构体
队列
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!
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.
Print the maximum total friendship factir that can be reached.
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
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,那么他们其中就会有一个不来,问你这个人最后收到的money最多是多少?
解题思路:
这儿要利用到结构体排序,然后找他们之间差值<d的人,求能够得到的的money的最大值
完整代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
using namespace std;
#define N 100010
#define ll long long
struct node
{
ll m,s;
}a[N],f;
bool cmp(node x,node y)
{
if(x.m==y.m)
return x.s<y.s;
return x.m<y.m;
}
int main()
{
ll n,d;
while(scanf("%lld%lld",&n,&d)!=EOF)
{
queue<node>q;
memset(a,0,sizeof(a));
for(int i=0;i<n;i++)
scanf("%lld%lld",&a[i].m,&a[i].s);
sort(a,a+n,cmp);
ll ans=0,sum=0;
for(int i=0;i<n;i++)
{
q.push(a[i]);
while(q.back().m-q.front().m>=d)
{
sum-=q.front().s;
q.pop();
}
sum+=a[i].s;
ans=max(ans,sum);
}
printf("%lld\n",ans);
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
#define N 100010
#define ll long long
struct node
{
ll m,s;
}a[N];
bool cmp(node x,node y)
{
if(x.m==y.m)
return x.s<y.s;
return x.m<y.m;
}
int main()
{
ll n,d;
while(scanf("%lld%lld",&n,&d)!=EOF)
{
memset(a,0,sizeof(a));
for(int i=0;i<n;i++)
scanf("%lld%lld",&a[i].m,&a[i].s);
sort(a,a+n,cmp);
int j=0;
ll ans=0,sum=0;
for(int i=0;i<n;i++)
{
while(a[j].m-a[i].m<d)
{
sum+=a[j].s;
ans=max(ans,sum);
j++;
if(j==n)
break;
}
sum=sum-a[i].s;
}
printf("%lld\n",ans);
}
return 0;
}